2016-12-05 128 views
0

我有一个像下面的一个在User模型的模型关系,添加“orWhere”到laravel雄辩模型关系

public function notifications(){ 
    return $this->morphMany('App\Notification','receiver') 
       ->orWhere('type', 2); 
} 

这种运作良好,如果没有其他条件。但是,如果$userUser一个实例,并且我叫喜欢,$user->notifications->where('status', 1);

查询条件为,

SELECT * FROM notifications其中notificationsreceiver_id = 3 和notificationsreceiver_id不为空并且 notificationsreceiver_type =用户或type = 2和status = 1

这里的问题是,最终的状态是工作为OR因为我无法组的关系的条件。因此,即使基础关系条件失败,但只有status & type字段匹配,它也会获取该记录。

我需要的是在关联条件之后的第一个where和close之后添加括号,以便任何其他应用条件的地方都不会影响基本查询。

我需要的:(。notificationsreceiver_id = 3 和notificationsreceiver_id不为空并且 notificationsreceiver_type =用户或type = 2

SELECT * FROM notifications其中status = 1

回答

1

结账Parameter Grouping

事情是这样的:

Notifications::where('receveier_id', '=', 3) 
->whereNotNull('receveier_id') 
->where(function ($query) { 
     $query->where('receiver_type', '=', 'User') 
      ->orWhere('type', '=', 2); 
}) 
->where('status', '=', 1); 
+0

谢谢!这工作,我知道参数分组。我的疑问是将morphMany包含在组中,并正在寻找解决方案,如@ kapil.dev的答案。不幸的是,这并没有奏效。 –

0

试试这个..

public function notifications(){ 
    return $this->where(function($query){ 
         $query->morphMany('App\Notification','receiver') 
          ->orWhere('type', 2); 
       }) 
} 

这个代码在型号

希望替换您的代码这部作品

+0

它没有! '调用未定义的方法Illuminate \ Database \ Query \ Builder :: morphMany()' –

+0

oohh,也许你可以手动编写所有SteD建议的条件在另一个答案 –

+0

谢谢!我这样做,它的工作。但我期待着这样的:) –