我正在学习Laravel的口才关系,我有一个问题,关于 hasonethrough
通过使用与Laravel的docs相同的表格设计
tables
mechanics (id, name)
cars (id, model, mechanic_id)
owners (id, name, car_id)
然后,我在机械师模型上定义关系,以访问车主
class Mechanic extends Model
{
public function carOwner() {
return $this->hasOneThrough('App\Owner', 'App\Car');
}
}
这将返回
array:4 [▼
"id" => 1
"name" => "Ricky"
"car_id" => 1
"laravel_through_key" => 1
]
我的问题是,我可以用我的汽车模型获得 hasOnethrough
关系表?
是的,你可以....
在你的车主模型中设置汽车关系
class Owner extends Model
{
public function car() {
return $this->belongsTo('App\Car','car_id');
}
}
那么你可以这样使用这些关系。
$value=Mechanic::find($mechanic_id)->with('carOwner.car')->get();
$value将持有车主与他的车。