我有4张桌子那样,
帖子
category_fields
category_field_options
post_fields_values
我的关系就是那样;
// Post model
public function values()
{
return $this->hasMany(PostFieldValue::class)->where('deleted_at',null);
}
// CategoryFeild
public function options()
{
return $this->hasMany(CategoryFieldOptions::class);
}
// CategoryFieldOptions model
public function category()
{
return $this->belongsTo(Category::class);
}
// PostFieldValue model
public function post()
{
return $this->hasOne(Post::class);
}
public function categoryField()
{
return $this->belongsToMany(CategoryField::class,
'category_category_fields', 'category_field_id', 'id')->wherePivot('deleted_at',null);
}
现在我正在使用此代码来过滤帖子,请查看vehicleType的if条件的注释行
$query = Post::with('values')->where('is_active', 1);
if ($request->has('postName') && isset($request->postName) ) {
$query->where('title', 'LIKE', '%' . $request->postName . '%');
$query->orWhere('id',$request->postName);
}
if ($request->has('vehicleType') && isset($request->vehicleType)) {
// How do I list posts according to the type of vehicle given ?
//for example, if vehicleType is bus, should be only listing bus posts...
}
$paginateNumber = 10;
if ($request->has('paginate') && isset($request->paginate)) {
if ($request->paginate == 25) {
$paginateNumber = 20;
} elseif ($request->paginate == 50) {
$paginateNumber = 50;
} elseif ($request->paginate == 100) {
$paginateNumber = 100;
}
}
$posts = $query->paginate($paginateNumber);
假设选择categories
时正在搜索vehicleType
,则可以使用->whereHas()
查询构建器方法来实现:
$query = Post::with('values')->where('is_active', 1);
if ($request->filled('postName')) {
$query = $query->where('title', 'LIKE', '%' . $request->postName . '%')
->orWhere('id',$request->postName);
}
if ($request->filled('categoryType')) {
$query = $query->whereHas('category', function($query) use ($request) {
$query = $query->where('name', $request->categoryType);
});
}
$posts = $query->paginate($request->input('paginate', 10));
[->filled()
将检查请求密钥是否存在于请求中,并且不为空/空。
您可以使用->whereHas()
检查post
是否具有category
,其中name
是类别类型中传递的内容。
最后,您可以使用$request->input('paginate', 10)
获取分页值以限制查询,或者返回默认值10
。
我希望这会有所帮助。