laravel 在 Eloquent 中将 withTrashed 与关系一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25868025/
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 10:06:58  来源:igfitidea点击:

Using withTrashed with relationships in Eloquent

phplaraveleloquent

提问by Vuk Stankovi?

Is there a way to use withTrashedwith relationships in Eloquent.

有没有办法withTrashed在 Eloquent 中使用关系。

What I need is this. I have table and model Markand another table User. Userhas many Markand Markbelongs to User. So I defined this in Eloquent models.

我需要的是这个。我有桌子和模型Mark以及另一张桌子UserUser有很多MarkMark属于User。所以我在 Eloquent 模型中定义了它。

Now I need to get an instance of Markthat is soft deleted. This is not a problem if Userisn't soft deleted, but if both Markand Userare soft deleted, I get an error Trying to get property of non-object, because

现在我需要得到一个Mark软删除的实例。这不是一个问题,如果User没有软删除,但如果同时MarkUser被软删除,我得到一个错误Trying to get property of non-object,因为

$mark->user

won't return actual user, cause it is soft deleted.

不会返回实际用户,因为它被软删除。

Is there a way that I can do something like

有没有办法让我做类似的事情

$mark->withTrashed()->user

to get this related user even if it is deleted?

即使删除了这个相关用户,也要获取它吗?

回答by Jarek Tkaczyk

Depenging on your needs, you can define the relationship:

根据您的需要,您可以定义关系:

public function marks()
{
  return $this->hasMany('Mark')->withTrashed();
}

// then just
$user->marks;

or use it on the fly:

或即时使用它:

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

// or when lazy/eager loading
$user = User::with(['marks' => function ($q) {
   $q->withTrashed();
}])->find($userId);

And in your pasted example it will be:

在您粘贴的示例中,它将是:

$mark->user() // get relation object first
   ->withTrashed() // apply withTrashed on the relation query
   ->first();  // fetch the user

// alternatively you use getResults relation method
$mark->user()
   ->withTrashed()
   ->getResults();  // returns single model for belongsTo

$user->marks()->withTrashed()
   ->getResults(); // returns collection for hasMany

回答by lowerends

You can do that like this:

你可以这样做:

$mark->withTrashed()->first()->user->withTrashed()->first()