Home » Php » php – Laravel 4: Where Not Exists

php – Laravel 4: Where Not Exists

Posted by: admin July 12, 2020 Leave a comment

Questions:

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');
    }
}
How to&Answers:

Something like

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