【问题标题】:Retrieving relationships from relationships in Laravel从 Laravel 中的关系中检索关系
【发布时间】:2020-08-20 14:56:03
【问题描述】:

我有一个使用 Laravel 7 的应用程序。在其中,我有一个“帐户”模型,这个模型有几个“配置文件”,每个“配置文件”有几个“产品”。

如何以最佳方式检索附加到某些“帐户”的所有“产品”。

目前,我加载链接到此“帐户”的所有“配置文件”,然后加载链接到每个“配置文件”的所有“产品”。但是我觉得这不是很优化,并且很难对返回的数据进行排序(按降序排列)。

我确信 Eloquent / Laravel 允许直接恢复它,但我不知道如何。

谢谢你!

【问题讨论】:

  • 您可以设置一对多关系并进行预加载

标签: php laravel eloquent laravel-7


【解决方案1】:

eloquent 仅针对这种情况具有“Has Many Through”关系, 在您的帐户模型中,您可以编写如下内容:

class Account extends Model
{
public function products()
{
return $this->hasManyThrough(Product::class, Profile::class);
}
}

现在,您可以获取指定帐户的所有产品,例如:

$myAccountProducts=Account::find($account_id)->products()->get();

你也可以指定外键...

更多细节在:

https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

【讨论】:

    【解决方案2】:
    Account::with(['profiles','profiles.products'])->get();
    

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 2019-12-11
      • 2022-07-27
      • 1970-01-01
      • 2020-08-23
      • 2016-02-25
      • 2022-01-10
      • 2020-08-23
      • 2023-03-26
      相关资源
      最近更新 更多