Laravel 4: Where Doesn't Exist

I need my model to return only those records from one table where the corresponding record does not exist in another table. I thought the solution could 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 | -------------------- 

Perhaps not necessary, 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'); } } 
+7
php mysql eloquent laravel
source share
1 answer

Something like

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

All Articles