您好,我在进行 Laravel 查询时遇到问题
模型区域
class Region extends Model
{
protected $table = 'regions';
protected $guarded = [
];
public function county()
{
return $this->belongsTo('App\Models\County');
}
public function companies()
{
return $this->belongsToMany('App\Models\CompanyInfo',
'region_company','region_id','company_id');
}
型号类别
class Category extends Model
{
protected $table = 'categories';
protected $guarded = [];
public function companies()
{
return $this->belongsToMany('App\Models\Company', 'categories_company','category_id','company_id');
}
}
模范公司
class Company extends Model
{
protected $table ='companies';
protected $guarded = [
];
public function regions()
{
return $this->belongsToMany('App\Models\Region', 'region_company','company_id','region_id');
}
}
我有一个输入表单,我想按类别和地区进行过滤,如果可能的话,输出应该是包含公司的类别,但我只想每个类别显示 10 家公司。不确定这是否可能。
这是我到目前为止所拥有的
$categories = $request->input('categories');
$region = $request->input('regions');
$companies = Category::whereIn('id',$categories)->with([
'companies.regions' => function ($query) use ($region) {
$query->whereIn('id', $region);
}])->get();
这里的问题是它正在过滤类别,但它仍然给我所有公司没有过滤掉属于特定区域的一次。
谢谢 丹妮
最佳答案
尝试以下操作:
$categories = $request->input('categories');
$region = $request->input('regions');
$companies = Category::whereIn('id',$categories)->with([
'companies' => function ($query) use ($region) {
$query->whereHas('region', function ($q2) use ($region){
$q2->whereIn('id', $region);
});
$query->with(['region']);
$query->limit(10);
}])->whereHas('companies', function($q) use ($region) {
$q->whereHas('region', function ($q2) use ($region){
$q2->whereIn('id', $region);
});
})->get();
关于php - 拉拉维尔 : Querying and accessing child objects in nested relationship with where clauses Many to Many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44701404/