Laravelで継承元モデルの$withを引き継ぎ、オーバーライドする
Model <- Bicycle <- ElectricBicycle
という継承関係で
Bicycleモデルで$withを使ってイーガーローディングしている
Bicycleモデルを継承したElectricBicycleモデルを作り、ElectricBicycle独自で実装したリレーションがあるとする
ElectricBicycleモデルでBicycleモデルの$with+独自実装したリレーションをイーガーローディングするためには以下のようにする
Bicycle
class Bicycle extends Model
{
$with = [
'handle'
];
public function handle()
{
return $this->hasOne(Handle::class);
}
}
ElectricBicycle
class ElectricBicycle extends Bicycle { public function __construct(array $attributes = []) { parent::__construct($attributes); $this->with = array_merge( $this->with, [ 'battery', ] ); } public function battery() { return $this->hasOne(Battery::class); } }