Thursday, January 31, 2019

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

One to Many Relationship

Demo details:

In this demo we have 2 models (Thief and Car), and 2 tables (thieves and cars).

Business Rules:

The Thief can steal many Cars.
The Car can be stolen by one Thief.

Relations Diagram:

Relationship Details:

The Cars table should store the Thief ID.

Eloquent Models:

class Thief
{
    public function cars()
    {
       return $this->hasMany(Car::class);
    }
}
class Car
{
    public function thief()
    {
        return $this->belongsTo(Thief::class);
    }
}

Database Migrations:

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

Store Records:

// Create relation between Thief and Car.
$thief->cars()->saveMany([
   $car1, 
   $car2,
]);
// Or use the save() function for single model.
$thief->cars()->save($car);
// Create relation between Car and Thief.
$car->thief()->associate($thief)->save();

Retrieve Records:

// Get Thief Car
$thief->cars;
// Get Car Thief
$car->thief;
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