Using withTrashed with relationships in Eloquent

2020-08-09 06:35发布

问题:

Is there a way to use withTrashed with relationships in 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.

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

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?

回答1:

Depending 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);

then your case would turn into:

$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


回答2:

You can do that like this:

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