2017-04-15 111 views
0

我想查詢哪裏isrecurring = 1在我的數據透視表中,但沒有找到現有的解決方案。任何人有任何經驗,以及如何獲得多對多數據透視表中的所有記錄'isrecurring'= 1Laravel:如何使用數據透視多態多對多

Example. 
$enroll->products->where('isrecurring', 1); 

but in enrollable pivot table 
-> get all records that 'isrecurring' = 1 

我的模型(不wherePivot)

Enroll.php 
------ 
public function products(){ 
return $this->morphedByMany('App\Models\Product', 'enrollable')->withPivot('isrecurring'); 
} 

Product.php 
---- 
public function enrolls(){ 
return $this->morphToMany('App\Models\Enroll', 'enrollable')->withPivot('isrecurring'); 
} 

我的數據庫

enrolls 
----- 
id 


products 
---- 
id 

enrollables 
---- 
enroll_id 
enrollable_id 
enrollable_type 
isrecurring (boolean) 

我希望用wherePivot,但似乎沒有工作,無法查詢。

Product.php 
---- 
public function enrolls(){ 
return $this->morphToMany('App\Models\Enroll', 'enrollable')->withPivot('isrecurring')->wherePivot('isrecurring', '=', 1); 
} 

回答

0

我有同樣的問題,並使用可以解決這個問題如下:

//Model: User.php 

public function certificates() 
{ 
    return $this->morphedByMany('App\Certificate', 'appliable') 
     ->withTimestamps(); 
} 

//Controller: EnrollmentController.php 

$usersWithCertificates = User::whereHas('certificates', function($query){ 
    $query->where('status', '0'); 
})->with('certificates')->latest()->paginate(10); 

使用function($query){ }添加的數據透視表的自定義SQL

你可以在這裏閱讀更多Laravel文檔: https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence在查詢關係存在部分

相關問題