Laravel : 在关系中搜索查询

Laravel : Search Query Within Relationship

当我在我的应用程序中添加一个新的 post 时,有一个 7 tables 会影响我添加单个 post 的时间。要获取所有 post 和所有 post 数据,我的简单查询如下所示:

$userPost   = Post::with(['product','postattribute.attribute.category','user.userDetails'])
                        ->offset($offset)
                        ->limit($limit)
                        ->whereStatus("Active")
                        ->whereIn('product_id', $userApprovalProductIDs)
                        ->orderBy('id','desc')
                        ->get();

所以它会重新运行我想要的所有数据。现在我想在所有 table 中实现搜索查询,目前我只能搜索 posts table.

如果我在 category table 上使用 categoryTitle 进行搜索,我会尝试像

这样编码
where('category.title','=', $serachTitle)

但它对我不起作用。

POST模型关系:

public function user() {
    return $this->belongsTo(User::class);
}

public function product() {
    return $this->belongsTo(Product::class);
}

public function postattribute() {
    return $this->hasMany(PostAttribute::class);
}

POSTATTRIBUTES模型关系:

  public function post() {
    return $this->belongsTo(Post::class);
}

 public function attribute() {
    return $this->belongsTo(Attribute::class);
}

ATTRIBUTES模型关系:

   public function category() {
    return $this->belongsTo(Category::class);
}

 public function attributes() {
    return $this->belongsTo(Attribute::class);
}

我该怎么做?

要对嵌套关系应用过滤器,您可以使用 whereHas

$userPost   = Post::with(['product','postattribute.attribute.category','user.userDetails'])
    ->offset($offset)
    ->limit($limit)
    ->whereStatus("Active")
    ->whereIn('product_id', $userApprovalProductIDs)
    ->whereHas('postattribute.attribute.category', function ($query) use($serachTitle) {
        $query->where('title', '=', $searchTitle);
    })
    ->orderBy('id','desc')
    ->get();

Querying Relationship Existence

从评论中我了解到您想知道如何在每个关系中搜索 post ,我已经添加了一个示例来搜索类别标题

->whereHas('postattribute.attribute', function ($query) use($var) {
    $query->where('some_field_of_attribute_table', '=', $var);
})

->whereHas('postattribute', function ($query) use($var) {
    $query->where('some_field_of_postattribute_table', '=', $var);
})