有一个通过拉拉维尔雄辩
我有三张桌子 , , .garages
cars
securities
证券是保持一辆汽车安全的证券,你可以拥有多个证券,但一个证券只能保证一辆汽车的安全。车库是汽车所在的地方,证券也是。
我想要的是列出所有的证券,并知道他所在的车库的名称。问题是没有包含车库ID的列,只有他保管安全的汽车的ID,但汽车有车库的ID。securities
Laravel Eloquent 有一个叫做 的方法,但只有一个通过。hasManyThrough
securities
garage
cars
以下是表格:
车库表:
-----------------------------------
|garage_id|garage_name|garage_size|
-----------------------------------
| 1| Garage 1| 200|
-----------------------------------
| 2| Garage 2| 400|
-----------------------------------
汽车表:
---------------------------
|car_id|car_name|garage_id|
---------------------------
| 1| Car 1| 1|
---------------------------
| 2| Car 2| 1|
---------------------------
| 3| Car 3| 2|
---------------------------
证券表:
----------------------------------
|security_id|security_name|car_id|
----------------------------------
| 1| Security 1| 1|
----------------------------------
| 2| Security 2| 1|
----------------------------------
| 3| Security 3| 2|
----------------------------------
| 4| Security 4| 3|
----------------------------------
输出必须为:
Security 1 is on Garage 1
Security 2 is on Garage 1
Security 3 is on Garage 1
Security 4 is on Garage 2
我有模型:
代码是列出车库,但我想做类似的,但列出证券(只是为了让你了解结构如何)。
$garages = Garages::with(['cars', 'securities'])->get();
$garages->transform(function($garages) {
return array(
'garage_name' => $garage->garage_name,
'count_cars' => $garage->cars->count(),
'count_securities' => $garage->securities->count(),
);
});
class Garages extends Eloquent
{
public function cars()
{
return $this->hasMany('cars');
}
public function securities()
{
return $this->hasMany('securities');
}
}
class Cars extends Eloquent
{
}
class Securities extends Eloquent
{
}
再次强调:我想让车库的名称与安全保护的汽车相关。
只是为了让它更容易理解,如果我这样做:
$securities = Securities::with(['cars'])->get();
class Securities extends Eloquent
{
public function cars()
{
return $this->hasOne('cars');
}
}
我将只从表中获取作为关系。我真正想要的是车库的名字。garage_id
cars
[relations:protected] => Array
(
[cars] => Cars Object
(
...
[attributes:protected] => Array
(
...
[car_name] => Car 1
[garage_id] => 1
...