class Owner { public function car() { return $this->hasOne(Car::class); } } class Car { public function owner() { return $this->belongsTo(Owner::class); } }
数据库迁移:
1 2 3 4 5 6 7 8 9 10
Schema::create('owners', function (Blueprint $table) { $table->increments('id'); $table->string('name'); }); Schema::create('cars', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('owner_id')->unsigned()->index()->nullable(); $table->foreign('owner_id')->references('id')->on('owners'); });
储存记录
1 2 3 4
// 在 Owner 及 Car 之间建立关联 $owner->car()->save($car); // 在 Car 及 Owner 之間建立关联 $car->owner()->associate($owner)->save();
获取记录
1 2 3 4
// 获取 Owner Car $owner->car; // 获取 Car Owner $car->owner;
class Thief { public function cars() { return $this->hasMany(Car::class); } } class Car { public function thief() { return $this->belongsTo(Thief::class); } }
数据迁移:
1 2 3 4 5 6 7 8 9 10
Schema::create('thieves', function (Blueprint $table) { $table->increments('id'); $table->string('name'); }); Schema::create('cars', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('thief_id')->unsigned()->index()->nullable(); $table->foreign('thief_id')->references('id')->on('thieves'); });
class Man { public function cars() { return $this->morphMany(Car::class, 'buyer'); } } class Woman { public function cars() { return $this->morphMany(Car::class, 'buyer'); } } class Car { public function buyer() { return $this->morphTo(); } }
class Driver { public function cars() { return $this->belongsToMany(Car::class); } } class Car { public function drivers() { return $this->belongsToMany(Driver::class); } }
数据库迁移:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Schema::create('drivers', function (Blueprint $table) { $table->increments('id'); $table->string('name'); }); Schema::create('cars', function (Blueprint $table) { $table->increments('id'); $table->string('name'); }); Schema::create('car_driver', function (Blueprint $table) { $table->increments('id'); $table->integer('car_id')->unsigned()->index(); $table->foreign('car_id')->references('id')->on('cars')->onDelete('cascade'); $table->integer('driver_id')->unsigned()->index(); $table->foreign('driver_id')->references('id')->on('drivers')->onDelete('cascade'); });
class Valet { public function cars() { return $this->morphToMany(Car::class, 'driver'); } } class Owner { public function cars() { return $this->morphToMany(Car::class, 'driver'); } } class Car { public function valets() { return $this->morphedByMany(Valet::class, 'driver'); }
public function owners() { return $this->morphedByMany(Owner::class, 'driver'); } }