【问题标题】:Laravel Eloquent ignore protected $with [duplicate]Laravel Eloquent 忽略受保护的 $with [重复]
【发布时间】:2021-05-02 06:41:32
【问题描述】:

所以基本上我有模型 foo:

protected $with = ['bars'];

public function bars()
{
   return $this->morphMany(bar::class, 'barable');
}

还有模型栏:

public function barable() 
{
   return $this->morphTo();
}

现在我的问题是,如果我想通过 bar 加载 foo:

Bar::find(1)->with(['barable.something.this'])->get();

我得到了 foo 表和相应的栏。

现在因为 foo 的 bar 属性有很多条目(包括我通过它请求 foo 的原始 bar),我想排除 barable.bars,但由于它包含在 with 属性中,所以它总是被加载。

如何从查询中排除 barable.bars?

编辑:如果这很重要,我正在使用 laravel 5.6

【问题讨论】:

  • 删除protected $with = ['bars'];
  • 问题是,这是我不需要条形图的唯一情况,在所有其他查询中我都需要条形图
  • 好的,在这种情况下,你可以使用makeHidden函数
  • 试过这样:Bar::find(1)->makeHidden(['barable.bars'])->with(['barable.something.this'])->get(); 但我得到Method Illuminate\Database\Query\Builder::makeHidden does not exist. 是一个错误

标签: php database laravel eloquent builder


【解决方案1】:

尝试使用$books = Book::without('author')->get();,就像写在documentation中一样。

所以你的情况是

Bar::find(1)->with(['barable' => function ($query){ $query->without('bars'); $query->with(['something.this']) }])->get();

【讨论】:

  • 如果我想使用 Books::find 或 Books::orderBy,我将如何实现?
  • 你可以这样试试吗? Books::find(1)->without('author')->get();Books::without('author')->orderBy('id')->get();
  • 如果我尝试像Books::find(1)->makeHidden(['barable.bars'])->with(['barable.something.this'])->get(); 我得到Method Illuminate\Database\Query\Builder::makeHidden does not exist 并使用Books::makeHidden(['streamable.streams'])->orderBy('id')->with(['barable.something.this'])->get(); 我得到:Non-static method Illuminate\Database\Eloquent\Model::makeHidden() should not be called statically
  • 你试过without而不是makeHidden的方法吗?
  • 如果你的意思是 Books::find(1)->without(['barable.bars'])->with(['barable.something.this'])->get() 它包括 barable.bars
猜你喜欢
  • 2016-11-03
  • 2017-10-16
  • 2011-06-27
  • 2014-02-08
  • 2014-12-02
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
相关资源
最近更新 更多