【问题标题】:Need relationship data in Laravel在 Laravel 中需要关系数据
【发布时间】:2017-06-05 10:07:38
【问题描述】:

所有 laravel 人,如果你能帮助我,请。我有数据库作为 PostgreSQL。我有四个表如下:

食物:ID、名称

好处:身份证、姓名

Benefit_rating:身份证、姓名

Food_benefit:ID、food_id、Benefit_id、Benefit_rating_id

当食物的 id 已知并且它从 Food 中获取食物名称 (Food.name) 并列出所有食物福利 (benefit_rating.name) 及其评级 (Benefit_rating.name) 时,我需要一个查询。

现在,了解 Food_benefit 包含与食物相关的食物、福利和福利等级之间的关系。

我不能有多对多的关系,因为数据透视表是这样设计的[不能改变设计]。

任何原始查询类型的东西建议?

【问题讨论】:

  • 您仍然可以拥有多对多。你可以有Food::belongsToMany(Benefit)Benefit::belongsToMany(Food)Benefit::belongsToMany(BenefitRating)BenefitRating::belongsToMany(Benefit),最后是Food::belongsToMany(BenefitRating)BenefitRating::belongsToMany(Food)。然后你可以这样做:Food::with('benefits.benefitRatings')->find($id).

标签: mysql laravel


【解决方案1】:

我假设您正在使用 Eloquent 并且已经定义了模型之间的关系。

你可以使用nested eager loading:

$food = Food::where('id', $foodId)
            ->with('foodBenefits.benefitRating', 'foodBenefits.benefit')
            ->first();

eager loading:

$food = Food::find($foodId);
$foodBenefit = FoodBenefit::where('food_id', $foodId)
                          ->with('benefit', 'benefitRating')
                          ->get();

【讨论】:

  • 赞!砰的一声。
猜你喜欢
  • 2021-06-14
  • 2015-03-11
  • 2017-03-06
  • 1970-01-01
  • 2014-12-22
  • 2021-10-31
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多