简体   繁体   English

Laravel 急切加载两个模型之间的关系导致其他模型之间的关系返回错误结果

[英]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).我有两个名为 Question and Answer 的 Eloquent 模型,它们之间存在一对多关系(一个问题有很多答案)。 The hasMany relationship in Question.php is called answers . Question.php 中的 hasMany 关系称为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:我还有一个用户和一个公司 model,它们之间存在多对多关系,它们使用 pivot model,这样定义:

User.php用户.php

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

Company.php公司.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:在 Question model 的 answers() 关系方法中,我需要获取当前用户的第一家公司才能修改关系:

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.我的应用程序中的大多数用户都有一个公司附属于他们,当使用急切加载时,虽然auth()->user()->companies返回的不是一个,而是 134 个公司,即使在数据库中我只有 5 个公司和当前用户只属于一个。 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.当我转储auth()->user()->companies集合的内容时,我看到第一家公司 model 存在 130 次,其他 4 家公司也包括在内。

This happens only in the answers() method and only when using eager loading.这仅发生在answers()方法中并且仅在使用急切加载时发生。 Any ideas why?任何想法为什么?

Environment:环境:

  • Laravel version: 6.20.6 Laravel 版本:6.20.6
  • PHP version: 8.0.1 PHP 版本:8.0.1
  • Apache: 2.4.26 Apache:2.4.26
  • DB: 10.1.27-MariaDB数据库:10.1.27-MariaDB

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.我通常做的是插入 ddd() 并检查查询选项卡以查看 Laravel 用于获取数据的查询。 This might shed some more light on the problem.这可能会更清楚地说明问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM