Laravel:以嵌套关系查询和访问子对象,其中where子句多对多关系

时间:2017-06-22 13:52:00

标签: php mysql laravel-5 eloquent

您好我的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();

这里的问题是它正在过滤类别,但它仍然让我所有公司都没有过滤掉属于某个区域的公司。

谢谢你 达尼

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

$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();