2017-06-22 56 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