【问题标题】:Laravel relations relationLaravel 关系关系
【发布时间】: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


【解决方案1】:

所以,如果您的数据库设置为...

users   user_plates   cars
-----   -----------   ----
id      id            id
etc.    plate         etc.
        user_id
        car_id

您的模型设置为...

// in model: User
public function user_plates() 
return $this->hasMany('UserPlate');  // fill out fully qualified name as appropriate…

// in model: UserPlate
public function user() 
return $this->belongsTo('User');

public function car()
return $this->belongsTo('Car');

// in model: Car
public function user_plates()
return $this->hasMany('UserPlate’);

要返回属于用户 $id 的汽车集合,您应该能够运行:

$cars = User::findOrFail($id)-> user_plates->pluck('car');

【讨论】:

  • 我确实将它添加到我的用户模型中,而不是我的控制器中。这是我的简报中的一个错误,感谢您指出。我更新了它。我做了你所描述的大部分事情,但我会仔细检查,因为特别是 $user->cars 是我正在寻找的,因为目前我正在检查车牌来接收汽车。我已经玩过 hasManyThrough 但我无法让它为我工作
  • 我认为我无法使 $user->cars 工作的主要原因可能是汽车表。这是外部的,买的,只有id,model,make,type,production_year,hsn_tsn作为字段。所以与用户没有关系。只有 user_plates 通过 user_id 和 car_id 与它有关系。 hasManyThrough 会是什么样子?我想,我必须指定另一个foreign_key,因为“汽车”没有plate_id也没有user_id?非常感谢您对正确方向的小提示。
  • 我认为 Eloquent 不会允许您建立 hasManyThrough 关系,因为 Eloquent 似乎希望汽车表上有一个外键。
猜你喜欢
  • 2015-11-13
  • 2013-04-19
  • 2020-07-31
  • 1970-01-01
  • 2016-02-12
  • 2020-10-24
  • 2017-10-21
相关资源
最近更新 更多