phplaraveleloquent

How to without re query modelA->relatedModelB->modelA


When Laravel Eloquent calls a relation property that indicates the original model of the relation destination from a certain model, it issues a re-query and returns the original model. Is there a way to return the original model without issuing a requery?

In posts->first()->author, laravel execute query select * from "users" where "users"."id" = ? limit 1.

I hope no execute query, and author returns $user.

https://laravelplayground.com/#/snippets/348b2dea-ac2a-423b-86c5-6ec17593546e

code image


Solution

  • without making a db query to load the author, when the author is the already loaded user, you can set the relation yourself

    Route::get('/', function() {
        $user = User::with(['posts'])->first();
        $user->posts->each(function (Post $post) use ($user) {
            $post->setRelation('author',  $user);
        });
    });
    

    now each post will have a author relation set on the current user.