2017-03-06 92 views
1

您好我是落實laravel框架 多晶型關係,目前我有2種型號 CreditLog和用戶Laravel使用morpMany與where子句

Creditlog擁有財產sourceable,這是sourceable到用戶模式

class CreditLog extends Model 
{ 
... 


    public function sourceable() 
    { 
     return $this->morphTo(); 
    } 

... 
} 

然後在用戶我有這樣的關係

class User extends Authenticatable 
{ 

    public function creditLogs() 
    { 
     return $this->morphMany('App\Models\CreditLog', 'sourceable'); 
    } 

} 

然後在一些控制器我需要得到用戶信用記錄

$user = User::find($id); 
$CreditLogs = $user->creditLogs; 

可以在添加參數creditLogs方法,我的意思是可以laravel morphMany添加參數這樣

$CreditLogs = $user->creditLogs 
         ->where('created_at', '>=', $inputReq['start']) 
         ->where('created_at', '<=', $inputReq['end']); 

感謝您迴應的問題

回答

1

您可以使用load()lazy eager loading

$user->load(['creditLogs' => function ($query) use($inputReq) { 
     $query->where('created_at', '>=', $inputReq['start']) 
       ->where('created_at', '<=', $$inputReq['end']); 
    }]); 

或者使用with() methid與Constraing eager loading