2017-06-22 99 views
0

您好我有一个问题嵌套关系访问子对象,使我laravel查询Laravel:查询并在WHERE子句多对多的关系

模型的区域

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

这里的问题是,它是过滤的类别,但它仍然让我无法滤除属于某一区域的一次所有公司。

谢谢 达尼

回答

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(); 
+0

嗨@ clod986感谢您的快速答复,但我得到一个错误的语法错误,意外“$查询”(T_VARIABLE)似乎之后$ q2-> whereIn('id',$ region); }它缺少我尝试过的东西;和,但还是同样的问题 – user1859876

+0

@ user1859876应该现在的工作,我忘了关语句 – clod986

+0

@ user1859876如果它给你一个“未定义的索引ID”的错误,与REGION_ID更换ID或REGIONS.ID – clod986