Thursday, January 31, 2019

Many 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

Many to Many Relationship

Demo details:

In this demo we have 2 models (Driver and Car), and 3 tables (driverscarsand a pivot table named car_driver).

Business Rules:

The Driver can drive many Cars.
The Car can be driven by many Drivers.

Relations Diagram:

Relationship Details:

The Pivot table “car_driver” should store the Driver ID and the Car ID.

Eloquent Models:

class Driver
{
    public function cars()
    {
       return $this->belongsToMany(Car::class);
    }
}
class Car
{
    public function drivers()
    {
        return $this->belongsToMany(Driver::class);
    }
}

Database Migrations:

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');
});

Store Records:

// Create relation between Driver and Car.
$driver->cars()->attach([
   $car1->id,
   $car2->id,
]);
// Or use the sync() function to prevent duplicated relations.
$driver->cars()->sync([
   $car1->id,
   $car2->id,
]);
// Create relation between Car and Driver.
$car->drivers()->attach([
   $driver1->id,
   $driver2->id,
]);
// Or use the sync() function to prevent duplicated relations.
$car->drivers()->sync([
   $driver1->id,
   $driver2->id,
]);

Retrieve Records:

// Get Driver Car
$driver->cars
// Get Car Drivers
$car->drivers
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