Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

eloquent - Laravel Eager loading of a relationship bettween two models causes a relationship between other models return wrong results

I have two Eloquent models named Question and Answer with one to many relationship between them (one question has many answers). The hasMany relationship in Question.php is called answers.

I also have a User and a Company model with a many to many relationship between them which uses a pivot model, defined this way:

User.php

public function companies()
{
    return $this->belongsToMany(Company::class)
        ->using(CompanyUser::class);
}

Company.php

public function users()
{
    return $this->belongsToMany(User::class)
        ->using(CompanyUser::class);
}

When I retreive a question and lazy load its answers:

Question::find(58)->answers;

Everything is okay. The problem comes when I use eager loading:

Question::with('answers')->get();

Something strange happens. In the answers() relationship method of the Question model, I need to get the current user's first company in order to modify the relationship:

auth()->user()->companies->first();

Most of the users in my application have one company attaches to them, when using eager loading though auth()->user()->companies returns not one, but 134 companies even though in the database I have only 5 companies and the current user belongs to only one. When I dumped the contents of the auth()->user()->companies collection I saw that the first company model is exists 130 times and the other 4 companies are also included.

This happens only in the answers() method and only when using eager loading. Any ideas why?

Environment:

  • Laravel version: 6.20.6
  • PHP version: 8.0.1
  • Apache: 2.4.26
  • DB: 10.1.27-MariaDB
question from:https://stackoverflow.com/questions/65869706/laravel-eager-loading-of-a-relationship-bettween-two-models-causes-a-relationshi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you need to get more information on the problem. What I normally do is insert ddd() and check the queries tab to see what queries Laravel is using to get the data. This might shed some more light on the problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...