Laravel 4: Where Not Exists

匿名 (未验证) 提交于 2019-12-03 02:01:02

问题:

I need my model to return only those records from one table where a matching record does not exist in another table. I was thinking that the solution might be with Query Scopes but the documentation only scratches the surface. So my SQL would look something like this:

SELECT * FROM A WHERE NOT EXISTS (SELECT A_id FROM B                 WHERE B.A_id = A.id) 

Here are my tables:

A ------------- | id | name | -------------  B -------------------- | id | A_id | name | -------------------- 

Probably unnecessary but here are my models. Model for A:

class A extends Eloquent{      public function B(){         return $this->hasOne('B', 'A_id', 'id');     } } 

Model for B:

class B extends Eloquent{      public function A(){         return $this->belongsTo('B', 'A_id', 'id');     } } 

回答1:

Something like

A::whereNotExists(function($query)             {                 $query->select(DB::raw(1))                       ->from('B')                       ->whereRaw('A.id = B.id');             })             ->get(); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!