Laravel从模型中获取数据,其中条件来自另一个模型


Laravel fetch data from model where the condtions is from another model

我有一个名为List的表,我计划用以下命令将其显示在视图中:$lists= List::with('user', 'product.photodb', 'tagCloud.tagDetail')->get();。但是,我希望显示的数据只是那些TagID等于一个用户输入的数据。这些数据可以从TagCloud表中检索。

我目前正在做的是:

$clouds = TagCloud::select('contentID')
                  ->where('tagDetailID', '=', $tagID)
                  ->get();
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
             ->where('id', '=', $clouds->contentID)
             ->get();

但是,当我尝试运行它时,它只返回一个null值,即使当我执行return $clouds时,它确实返回了所需的ID。

我哪里做错了?感谢您的帮助!

当前解决方案的几个问题。

  1. 使用get()返回一个Illuminate'Database'Eloquent'Collection对象。因此,您不能直接使用$clouds->contentID,因为$clouds是一个集合(如果您愿意,也可以是数组)。请参阅收藏文档
  2. where(...)希望第三个参数是字符串整数,也就是单个值。相反,您正在传递一个collection,它不起作用

正确的方法是使用whereHas(),它允许您筛选一个热切加载的关系。

最终代码:

$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
            ->whereHas('tagCloud',function($query) use ($tagID) {
                return $query->where('contentID','=',$tagID);
            })
            ->get();

参见WhereHas文档。

您想要的是whereHas()

$list = List::with(...)
    ->whereHas('relation', function($q) use($id) {
        return $q->where('id', $id);
    })->get();

在标签中应用Where条件云模型方法标签细节

public function tagDetail(){
    return $q->where('id', $id);
}