使用与雄辩的关系 [英] Using withTrashed with relationships in Eloquent

查看:96
本文介绍了使用与雄辩的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to use withTrashed with relationships in Eloquent.

我需要的是这个。我有表和模型标记和另一个表用户用户有许多标记标记属于用户。所以我在Eloquent模型中定义了这一点。

What I need is this. I have table and model Mark and another table User. User has many Mark and Mark belongs to User. So I defined this in Eloquent models.

现在我需要得到一个软删除的 Mark 的实例。如果用户不被软删除,但如果标记用户软删除,我收到错误尝试获取非对象的属性,因为

Now I need to get an instance of Mark that is soft deleted. This is not a problem if User isn't soft deleted, but if both Mark and User are soft deleted, I get an error Trying to get property of non-object, because

$mark->user

t返回实际用户,因为它是软删除。

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?

推荐答案

根据你的需要,你可以定义关系: p>

Depenging on your needs, you can define the relationship:

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

// then just
$user->marks;

或即时使用:

$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

这篇关于使用与雄辩的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆