Thursday, January 31, 2019

Polymorphic One to Many Relationship

No comments
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 (menwomen 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.
$man->cars()->saveMany([
   $car1, 
   $car2,
]);
$woman->cars()->saveMany([
   $car1, 
   $car2,
]);
// Or use the save() function for single model.
$man->cars()->save($car);
$woman->cars()->save($car);
// Create relation between Car and buyer (Men/Women).
$car1->buyer()->associate($man)->save();
$car2->buyer()->associate($woman)->save();

Retrieve Records:

// Get buyer (Man/Woman) Cars
$men->cars
$women->cars
// Get Car buyer (Man and Woman)
$car->buyer
Try this it will help you and for more information click here: Laravel Examples.

Read :

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