DMS-KH
DMS-KH

Reputation: 2787

how to use where for relationship in laravel eloquent?

I want to use where clause on the another relationship not my current selecting model as below table

table Customer
-------id-----customer_name

Table ModelA


table Customer
-------id-----fk_custome_id

table ModelB
-------id-----fk_ModelA_id

Function in Controller

$data['data'] = customer::with(['modelA','modelA.modelB'])
 ->where('fk_customer_id', 2)->get();

Customer Model

final function ModalA (){
    return $this->hasMany('App\Models\ModelA', 'fk_customer_id', 'id');
}

ModelA Model

final function Modelb (){
    return $this->hasMany('App\Models\ModelB', 'fk_modelA_id', 'id');
}

Error: I will got error as below because select sql don't find the column name fk_customer_id in table customer, So how can I user fk_customer_id (in table ModelA) for where.

Upvotes: 0

Views: 32

Answers (1)

Filip Koblański
Filip Koblański

Reputation: 9988

You can useYou can use whereHas like:

$data['data'] = customer::with(['modelA','modelA.modelB'])
     ->whereHas('modelA', function ($query) {
         $query->where('fk_customer_id', 2);
     })->get();

It's because when you're using with you just eager load constrints but you won't attach it to the main query (of the customer model). So there are two way: one modern with using whereHas or using join queries.

Upvotes: 1

Related Questions