【问题标题】:Speed up query through laravel relationships通过 laravel 关系加速查询
【发布时间】:2019-09-30 11:15:56
【问题描述】:

有 3 种型号:

First (first_id)
Connection (connection_id, first_id, product_id)
Second (second_id, product_id)

我想使用 laravel 关系将三个模型连接在一起

First->通过first_id加入连接 Connection->通过first_id加入First,并通过product_id加入Second Second -> 通过product_id 加入连接

所以:首先通过连接first_idproduct_id 加入第二个

这可以使用HasManyThrough 之类的东西吗?

感谢您的宝贵时间

【问题讨论】:

    标签: php laravel laravel-5 eloquent eloquent-relationship


    【解决方案1】:

    在您的第一个模型上:

    public function second () {
        return $this->hasManyThrough(
            Second::class, 
            Connection::class, 
            'product_id', // Foreign key on connection table
            'product_id', // Foreign key on second table
            'first_id', // Local key on first table
            'first_id' // Local key on connection table
        );
    }
    

    根据您的描述,列名应该可以工作。

    在修补程序中,您可以通过执行First::first()->second 之类的操作来验证它是否正确连接。

    【讨论】:

    • 现在完美运行,谢谢!
    【解决方案2】:

    这取决于您的第一个模型和第二个模型共享什么类型的关系,以及第二个和第三个模型共享什么类型的关系。

    如果考虑您的第一个模型First 和第二个模型Second 共享一对一关系,并且Second 模型和Third 模型共享一对一关系。

    它将是$first->second->third; //没有很多直通关系要求

    如果您的 First 模型和 Second 模型共享为 hasMany-belongs 关系而不是您需要使用 hasManyThrough 关系

    来自doc的示例

    class Country extends Model
    {
        public function posts()
        {
            return $this->hasManyThrough(
                'App\Post',
                'App\User',
                'country_id', // Foreign key on users table...
                'user_id', // Foreign key on posts table...
                'id', // Local key on countries table...
                'id' // Local key on users table...
            );
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用嵌套关系。

      嵌套预加载 要急切加载嵌套关系,您可以使用“点”语法。例如,让我们在一个 Eloquent 语句中急切地加载本书的所有作者和作者的所有个人联系人:

      $books = App\Book::with('author.contacts')->get();
      

      图书模型:

      public function author() 
      {
          return $this->hasOne('App\Author');
      }
      

      作者模型:

      public function contacts() 
      {
          return $this->hasMany('App\Author');
      }
      

      文档:

      https://laravel.com/docs/5.8/eloquent-relationships

      【讨论】:

        猜你喜欢
        • 2021-07-23
        • 1970-01-01
        • 2014-12-10
        • 2017-11-18
        • 1970-01-01
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多