当我在应用程序中添加新帖子时,有一个 7 个表格
会影响我添加单个帖子的时间。要获取包含所有帖子数据的所有帖子,我的简单查询如下所示:
$userPost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->offset($offset)
->limit($limit)
->whereStatus("Active")
->whereIn('product_id', $userApprovalProductIDs)
->orderBy('id','desc')
->get();
所以它会重新运行我想要的所有数据。现在我想在所有表中实现搜索查询,目前我只能搜索 posts
表。
如果我使用 categoryTitle
在 category
表上进行搜索,我会尝试编写类似的代码
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
从评论中我了解到,您想知道如何在每个关系中搜索帖子,我已经添加了一个使用类别标题进行搜索的示例
->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);
})
关于拉拉维尔 : Search Query Within Relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673837/