2017-01-02 156 views
1

我有简单的MAILDATA模式和邮件模式过滤通过相关模型的领域Laravel雄辩

这是MAILDATA关系:

function mail(){ 
    return $this->belongsTo(Mail::class); 
} 

,这里是我的查询:

$m = MailData::where('user_id', $userId)->orderBy('created_at', 'DESC')->take(10)->get(); 

但我想按邮件模式中的字段'收藏'过滤。我怎样才能做到这一点?

回答

1

如果你婉筛选,只有那些得到的数据,你可以使用

$m = MailData::with('mail')->whereHas('mail', function ($q) use ($value) { 
     $q->where('favorite', $value); 
    }) 
     ->where('user_id', $userId)->orderBy('created_at', 'DESC')->take(10)->get(); 
+0

,我可以通过'your_value'在这个函数? – zbyshekh

+0

是的,回答更新,请检查 – shoieb0101

+0

,这正是我需要的,非常感谢你 – zbyshekh

1

你可以这样做。

$m = MailData::with('mail')->whereHas('mail',function($q) use($v){ 
      //filter the field favorite here.. 
      //example 
      $q->where('favorite','like',$v); 
     })->where('user_id', $userId)->orderBy('created_at', 'DESC')->take(10)->get(); 
+0

,我可以在此功能通过“东西”价值? – zbyshekh

+0

'$ v'是你的过滤值。答复编辑。 @zbyshekh –