Vincent Dapiton
Vincent Dapiton

Reputation: 587

Laravel: Query child using parent information

I have a parent table and a child table, I was able to connect them using the belongsTo in the model.

Child Model 

public function item()
    {
        return $this->belongsTo('App\Models\ParentModel', 'parent_id', 'id');
    }
Parent_Table Child_Table
id id
entity parent_id
item_name
item_description

What i want to do is to query my Child Table using the parent info but I can't seem to make it work

ChildModel::where(item.entity, '$entity')->get();

Upvotes: 0

Views: 1173

Answers (1)

John Lobo
John Lobo

Reputation: 15319

Your relationship will be

public function item()
{
        return $this->belongsTo(ParentModel::class, 'parent_id', 'id');
}

and in query use wherehas to check entity

ChildModel::with('item')->whereHas('item',function($query)use($entity){
    $query->where('entity',$entity);
})->get();

Upvotes: 2

Related Questions