Hi Dear Friends,
In this post We would like to share infinity knowladge My Good experience and Best solution For .
Laravel Examples
Polymorphic Many to Many Relationship
Demo details:
In this demo we have 3 models (Valet, Owner and Car), and 4 tables (valets, owners,cars and drivers).
Business Rules:
The Valet (driver) can drive many Cars. The Owner (driver) can drive many Cars. The Car can be driven by many drivers (Valet or/and Owner).
Relations Diagram:
Relationship Details:
The Pivot table “drivers” should store the DriverID, DriverType and the CarID. “driver” is a name given to a group of models (Valet and Owner). And it’s not limited to two. The driver type is the real name of the model.
Eloquent Models:
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');
}
}
Database Migrations:
Schema::create('valets', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('owners', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('drivers', function (Blueprint $table) {
$table->increments('id');
$table->integer('driver_id')->unsigned()->index();
$table->string('driver_type');
// or use $table->morphs(‘driver’); instead of "driver_id" and "driver_type"
I hope you like this Post, Please feel free to comment below, your Any
Idea, suggestion and problems if you face - I am here to Resolve your
Any problems.
We hope it can help you...
No comments :
Post a Comment