Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: Where Not Exists

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');
    }
}
like image 294
sterfry68 Avatar asked Mar 14 '14 15:03

sterfry68


People also ask

What is whereNotIn in laravel?

Its simply means that you have an array of values and you want record except that values/records. you can simply pass a array into whereNotIn() laravel function. With query builder $users = DB::table('applications') ->whereNotIn('id', [1,3,5]) ->get(); //will return without applications which contain this id's.

Is query Builder faster than eloquent?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

What is pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

How do you get Join results as an array of objects in laravel?

$shop = Shop::leftJoin('ratings', 'ratings. shop_id', '=', 'shops.id') ->select('shops. *', 'ratings. rating')->get(); return response($shop);


1 Answers

Something like

A::whereNotExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from('B')
                      ->whereRaw('A.id = B.id');
            })
            ->get();
like image 108
marcanuy Avatar answered Sep 28 '22 05:09

marcanuy