Laravel eagerload a custom query instead of relationship

- 1 answer

Ad

I have a query that I want to eager load but its not working.

I have previously eager loaded relationships and its worked fine but this keeps giving me this error:

Call to a member function addEagerConstraints() on null

My function in the model:

public function update_image()
{
    return UpdateItem::where('type', 'image')->where('update_id', $this->id)->first();
}

And its called:

$updates = Update::with('project', 'update_items', 'update_image')->get();

I know the query itself is fine, but where is this going wrong?

Ad

Answer

Ad

as far as I know you can't eager load anything but relationships, but you can add your query to the relationship: in this case (I'm assuming it's one to one based on your question).

public function update_image()
{
     return $this->hasOne('App\UpdateItem','update_id','id')->where('type', 'image');
}
Ad
source: stackoverflow.com
Ad