Smartapiary's avatar

With a hasMany relationship, how to get only the parents without the children?

I have models with hasMany relationship and everything works well. But I have a huge amount of children datas and when I want to load only a list of all the parents it take a long time (due to the quantity of children records and performances of my database) to get the result.

I would like to know I to fetch the a list of all the parents, but without querying the children.

Something like : Parents::all()->withoutAnyChildren

0 likes
3 replies
pmall's avatar

I don't understand. Parent::all() return only parent models. If you don't ask eloquent to retrieve relationship it wont.

bobbybouwmann's avatar
Level 88

Do you maybe have the property $with set on your Parent model?

class Parent extends Model
{
    /**
     * The relations to eager load on every query.
     *
     * @var array
     */
    protected $with = [
        'children',
    ];
}

If so you should remove it and only call it when you need it ;)

Smartapiary's avatar

Thanks bobby it was exactly my problem!

Solved!

cheers

Please or to participate in this conversation.