php - 在 Eloquent 关系中使用 withTrashed

标签 php laravel eloquent

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

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

现在我需要获取一个软删除的 Mark 实例。如果 User 没有被软删除,这不是问题,但如果 MarkUser 都被软删除,我会收到错误 试图获取非对象的属性,因为

$mark->user

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

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

$mark->withTrashed()->user

即使被删除也能得到这个相关用户?

最佳答案

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

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

那么你的情况会变成:

$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

关于php - 在 Eloquent 关系中使用 withTrashed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25868025/

相关文章:

php - MorphTo Laravel Nova

php 1 是一个字符串而不是整数

php - 将带有回车键的 json 发送到 php web 服务

php - 将 Assets 文件添加到 Laravel 现有元素

laravel - 在运行时更改服务配置参数

php - Laravel:如何制作列名的键?

php - 在 PHP 中创建简单的 Google 日历事件

php - 仍然显示相同的错误: cURL error 60: SSL certificate problem: unable to get local issuer certificate

php - Laravel,在保存过程中创建额外记录的特征?

php - Laravel 5.2 Eloquent 地在同一 id 上保存自动增量 pgsql 异常