【发布时间】:2020-02-22 11:51:20
【问题描述】:
我对 Laravel Eloquent 模型和关系有一个理解问题。
我有一个用户表user。这些用户可以添加车牌,我保存在user_plates。我有一个包含汽车型号和类型的数据库。表名是cars。我有模型 App\User、App\UserPlates 和 App\Car。
user_plates 表具有字段id,plate,user_id,car_id。
我保存了车牌、关联的用户(在 user_id 中)和选定的汽车(car_id (id from table cars))
我将plates() 和belongTo 函数添加到我的用户模型中,该模型已经成功返回与该用户关联的所有车牌。但现在我想获取关联的汽车(user_plates 中的 car_id)。如何使用 Eloquent 实现这一目标? car表和user表没有任何联系,只有user_plates有car_id和user_id。
我需要做到这一点:
User -> Plates (can be multiple) -> Plate -> Car。我知道如何使用简单的 MySQL Joins 来实现这一点,但我想用 Eloquent 做到这一点。感谢您的帮助!
Laravel:6.4.0
【问题讨论】:
-
如何在 UserPlates 中定义与相关汽车的新关系?您将获得以下汽车:用户#1 > [车牌#1 > 汽车,车牌#2 > 汽车] 以此类推
-
是的,在我的 UserPlates 中添加一个带有 $this->belongTo(App\Car) 的函数 car() 是可行的,但现在我必须遍历它才能将它作为 JSON 返回。有什么聪明的方法可以做到这一点吗?我对 laravel 很陌生。
-
不清楚你想通过迭代来做什么!
-
我有一个端点,它将返回用户车牌及其相关汽车。
-
使用
load方法而不是with,你不需要使用get,所以你可以像$request->user()->load('plates.car');那样做
标签: php laravel eloquent foreign-keys relationship