laravel - Laravel 有一个通过
问题描述
在 laravel.com 上,有一个通过关系的示例,这几乎正是我所需要的。
https://laravel.com/docs/master/eloquent-relationships#has-one-through
mechanics
id - integer
name - string
cars
id - integer
model - string
mechanic_id - integer
owners
id - integer
name - string
car_id - integer
我的数据库结构完全一样。但是:在这个例子中,我认为每辆车都有一个所有者。我的问题是,我的车主有很多车,所以数据库有一点不同:
mechanics
id - integer
name - string
cars
id - integer
model - string
mechanic_id - integer
owner_id - integer
owners
id - integer
name - string
因此,代码示例不起作用:
class Mechanic extends Model
{
/**
* Get the car's owner.
*/
public function carOwner()
{
return $this->hasOneThrough(Owner::class, Car::class);
}
}
您是否有想法,如何更改接收代码:
//The mechanic
echo $mechanic->name;
//The cars the mechanic is working on
foreach ($mechanic->cars as car) {
echo $car->model;
//The owner of the car (Maybe like this???)
echo $car->model->owner->name;
}
解决方案
我不认为你想要 hasOneThrough 关系,除非你对一辆车感兴趣,而不是对机械师相关的每辆车感兴趣。
//The mechanic Model
dump($mechanic);
//The mechanic's name attribute
dump($mechanic->name);
//The Collection of cars associated with the mechanic
dump($mechanic->cars);
// echoing the model attribute of the cars associated with the mechanic
foreach ($mechanic->cars as $car) {
echo $car->model;
}
// The owner of ONLY the first car associated with the mechanic
dump($car->carOwner);
// echoing the model attribute of the cars associated with the mechanic and the car owner's name;
foreach ($mechanic->cars as $car) {
echo $car->model;
echo $car->owner->name;
}
// Eager loading both cars and associated owners from the Mechanic model:
Mechanic::with('cars.owner')->...
// or
$mechanic->load('cars.owner');
推荐阅读
- unity3d - 使用 UFPS 和 Inventory Pro 时如何在 Unity 中锁定光标?
- scala - build.spark:添加火花依赖
- node.js - 如何防止由于刷新导致的多个用户输入(Node JS)
- python - 不和谐机器人上的 YouTube 搜索
- c# - IActionResult .Net Core 上的默认参数
- html - Rotativa 不显示所有内容
- python - 添加 Keras Lambda 层后获取新输出?
- java - 在抽象方法中抓取参数
- java - 使用有效数字的 BigDecimal 除法
- python - 在 Pandas 中读取 CSV 时忽略一行