在Eloquent中使用withTrashed和关系

Vuk*_*vić 18 php laravel eloquent

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

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

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

$mark->user
Run Code Online (Sandbox Code Playgroud)

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

有没有办法让我能做点什么

$mark->withTrashed()->user
Run Code Online (Sandbox Code Playgroud)

获取此相关用户即使被删除?

Jar*_*zyk 53

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

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

// then just
$user->marks;
Run Code Online (Sandbox Code Playgroud)

或者在飞行中使用它:

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

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

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

$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
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢 (2认同)

low*_*nds 4

你可以这样做:

$mark->withTrashed()->first()->user->withTrashed()->first()
Run Code Online (Sandbox Code Playgroud)