Hi Dear Friends,
In this post We would like to share infinity knowladge My Good experience and Best solution For .
Laravel Examples
Polymorphic One to Many Relationship
Demo details:
In this demo we have 3 models (Man, Woman and Car), and 3 tables (men, women and cars).
Business Rules:
The Man (buyer) can buy many Cars. The Woman (buyer) can buy many Cars. The Car can be bought by one buyer (Man or Woman).
Relations Diagram:
Relationship Details:
The Car table should store the Buyer ID and the Buyer Type. “buyer” is a name given to a group of models (Man and Woman). And it’s not limited to two. The buyer type is the real name of the model.
Eloquent Models:
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();
}
}
Database Migrations:
Schema::create('men', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('women', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('buyer_id')->unsigned()->index()->nullable();
$table->string('buyer_type')->nullable();
// or use $table->morphs(‘buyer’); instead of "buyer_id" and "buyer_type"
});
Store Records:
// Create relation between buyer (Man/Woman) and Car.
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