晚安堆垛车,
我试图了解如何使用模型在laravel中建立以下关系:
我希望能够创建既可以是汽车也可以是摩托车的分类。
class Classified extends Model
{
public function classified()
{
return $this->morphTo();
}
}
class Car extends Model
{
public function classified()
{
return $this->morphOne(Classified::class, 'vehicle');
}
}
我的问题是:如何使用关系从分类广告中检索车辆信息?
谢谢!
答案 0 :(得分:1)
将classified()
方法重命名为vehicle()
(作为类型和ID列前缀):
class Classified extends Model
{
public function vehicle()
{
return $this->morphTo();
}
}
然后:
$classifieds = Classified::all();
foreach($classifieds as $classified){
$classified->vehicle->name;
}
创作:
$car->classified()->create([
'name' => '...'
])
$motorcycle->classified()->create([
'name' => '...'
])
或类似的行为谷Classified
模型:
$classified = Classified::create([
'vehicle_id' => $car->id,
'vehicle_type' => $car->getMorphClass(),
'name' => '...'
]);