【问题标题】:Laravel 5.6: Car has many colours has many images. When trying to find all "red" images for car 1, I get red images for all carsLaravel 5.6:汽车有很多颜色有很多图像。当试图找到汽车 1 的所有“红色”图像时,我得到所有汽车的红色图像
【发布时间】:2018-07-19 03:06:00
【问题描述】:

我有三个模型:

Car.phpColour.phpImage.php

它们有以下关系:

Car belongsToMany Colour:因为汽车可以有多种颜色。

Colour belongsToMany Car:因为一种颜色可以出现在很多车上。

Car belongsToMany Image:因为一辆车可以有多个图像。

Image belongsToMany Car:因为一张图片可以被多辆汽车使用。

Image belongsTo Colour:因为每张图片都必须有颜色。

Colour hasMany Image:因为红色可以在很多图片中找到。

如果我写 Car::find(1)->load('colours.images); 它会按预期返回所有关联的颜色,但是每种颜色都有 每个 使用该颜色的图像。所以我会看到红色的汽车 1、2、3 等,而不仅仅是汽车 1 的图像。

colours.images 似乎忽略了最初的汽车。

我做错了什么?

【问题讨论】:

  • 你能发布一些示例数据和预期的结果吗?

标签: php laravel eloquent relational-database eager-loading


【解决方案1】:

尝试类似 Car::find($id)->with(['colours.images' => function ($query) { $query->where('car_id', $id); }])

【讨论】:

  • withfind 之前
  • Color和Image的关系没有使用car_id,所以这个不行。
【解决方案2】:

您需要的是HasManyThrough 关系,但问题是您的汽车、颜色和图像是多对多关系(hasManyThrough 仅适用于一对多关系嵌套)。

查看this answer 了解更多信息和可能的解决方法。

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多