制作产品列表和过滤页面。所以我需要在laravel动态查询。但是当我尝试其中时与whereHas在select result中缺少一些产品。我的代码如下。目前我有3个主要类别,她的id是1,2,3。
控制器
$input = $request->all();
$products = Product::with('getMainCategory')->where('price', '>', $input['min'])->where('price', '<', $input['max']);
$keys = [1, 2, 3];
$products->whereHas('getMainCategory', function ($query) use ($keys) {
$query->whereIn('main_category_id', $keys);
});
$products = $products->get();
<?php
namespace AppModelsProductModel;
use AppModelsMainCategoryModelMainCategory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $guarded = [];
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
public function getMainCategory() {
return $this->belongsTo('AppModelsMainCategoryModelMainCategory', 'id', 'main_category_id');
}
}
子查询应该是
$query->whereIn('id', $keys);
但是你可以跳过这些,直接写
$input = $request->all();
$keys = [1, 2, 3];
Product::whereIn('main_category_id', $keys)->where(['price >' => $input['min'], 'price <' => $input['max']])->with(['getMainCategory'])->get();
同时,按照@JohnLobo的建议检查文档中的foreign_key和local_key顺序。