Laravel 雄辩与 Trashed 的关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51654757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:56:53  来源:igfitidea点击:

Laravel eloquent with Trashed on relationship

phplaravellaravel-5eloquent

提问by S_R

I need to be able to get a Models Relationship including its soft deleted elements, but only for this 1 instance. I do not want to change the model so that every time I use the relationship it returns all the soft deleted records too.

我需要能够获得包括其软删除元素在内的模型关系,但仅限于此 1 个实例。我不想更改模型,以便每次使用关系时它也会返回所有软删除的记录。

How can I achieve this?

我怎样才能做到这一点?

User Model

用户模型

class User extends Authenticatable
{
  public function contacts(){
    return $this->hasMany('App\Contacts','user_id','id');
  }
}

Controller

控制器

$user = User::findOrFail($id);
//Need to be able to get the trashed contacts too, but only for this instance and in this function
$user->contacts->withTrashed(); //Something like this
return $user;

How can I get the trashed rows only this 1 time inside my controller?

我怎样才能在我的控制器中只获得这 1 次垃圾行?

Thanks

谢谢

回答by Pusparaj

You can use withTrashedmethod in different ways.

您可以withTrashed以不同的方式使用方法。

To associate the call with your relationship you can do as follows:

要将呼叫与您的关系相关联,您可以执行以下操作:

public function roles() {
    return $this->hasMany(Role::class)->withTrashed();
}

To use the same in the fly:

在飞行中使用相同的:

$user->roles()->withTrashed()->get();

For your special scenario:

对于您的特殊情况:

$user->contacts()->withTrashed()->get();

回答by Robin Dirksen

You can do this with:

你可以这样做:

$user = User::findOrFail($id);

$user->contacts()->withTrashed()->get(); //get all results

return $user;

When you call the relation with (), you can append the withTrashed()method. After that you need to get()the results.

当您使用 调用关系时(),您可以附加该withTrashed()方法。之后,你需要get()的结果。

回答by Oluwatobi Samuel Omisakin

Looking at the Laravel Documentation on Querying soft deleted models:

查看有关查询软删除模型的 Laravel 文档:

//The withTrashed method may also be used on a relationship query: 
$flight->history()->withTrashed()->get(); 

The problem is using $user->contactsreturns collection of related records of contacts to user, while $user->contacts()will make a new query.

问题是使用$user->contacts将联系人相关记录的集合返回给用户,同时$user->contacts()会进行新的查询。