【问题标题】:Laravel HasManyThrough relationship while including Trashed itemsLaravel HasManyThrough 关系,同时包括已删除的项目
【发布时间】:2020-05-23 06:56:33
【问题描述】:

我想包含具有 HasManyThrough 关系的软删除项目,

我尝试在其中添加->withTrashed();,但随后出现此错误:

BadMethodCallException 调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasManyThrough::withTrashed()

是否可以强制 Laravel 在关系中跳过 where table.deleted_at is null

【问题讨论】:

  • 您能否在此处发布有关您的关系的代码?
  • 能否请您添加您的模型/控制器?

标签: php mysql laravel


【解决方案1】:

这是一个老问题,但对任何有同样问题的人都可以回答。

如果您正在使用 HasManyThrough 并且还想获取软删除的记录。 HasManyThrough 关系中有一个范围可以包含它们。 你应该像下面这样使用它:

$yourModel->yourHasManyThroughRelation()->withTrashedParents()->withTrashed();

【讨论】:

    【解决方案2】:

    应该按照您尝试的方式工作。 我做了一个例子让大家更清楚理解:

    Group::with('users')->get();

    Group 模型中:

    public function users()
    {
        return $this->hasManyThrough(User::class, UserGroup::class, 'group_id', 'id', 'id', 'user_id')->withTrashed();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2019-02-12
      • 2018-07-24
      • 2018-10-18
      • 2023-03-09
      • 2018-04-15
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多