A quick reference for Laravel’s Eloquent ORM 5.5

One-to-one correlation

Example details:

In this demonstration, we have two models (Owner and Car) and two tables (owners and CARS).

Business logic:

A user can own a car. A car can have one owner.

Associated graph:

Association Details:

The TABLE Cars must store the Owner ID.

Eloquent model:

class Owner
{
    public function car()
    {
       return $this->hasOne(Car::class);
    }
}
class Car
{
    public function owner()
    {
        return $this->belongsTo(Owner::class); }}Copy the code

Data migration:

Schema::create('owners'.function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});
Schema::create('cars'.function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->integer('owner_id')->unsigned()->index()->nullable();
    $table->foreign('owner_id')->references('id')->on('owners');
});
Copy the code

Storage Records:

// Create an association between Owner and Car$owner->car()->save($car); // Establish an association between Car and Owner$car->owner()->associate($owner)->save();
Copy the code

Obtain records:

// Get Owner Car$owner->car; // Get the Car Owner$car->owner;
Copy the code

One-to-many association

Example details:

In this example, we have two models: Thief and Car, and two tables: thieves and Cars.

Business rules:

Thieves can steal multiple cars. The car can only be stolen by one thief.

Diagram:

Relationship details:

The vehicle table should store the thief’s ID.

Eloquent model:

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

Data migration:

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

Record storage:

// Create an association between the thief and the car.$thief->cars()->saveMany([
   $car1.$car2,]); // Or call save() in a single model.$thief->cars()->save($car); // Create an association between Car and Thief.$car->thief()->associate($thief)->save();
Copy the code

Pull record:

// Get the car the thief stole$thief->cars; // Get the thief who stole a car$car->thief;
Copy the code

Polymorphic one-to-many relationships

Demo details:

In this demo, we have three models (Man, Woman, and Car), and three tables (Man, women, and cars).

Business rules:

A man can buy a lot of cars. One woman can buy a lot of cars. The car can be purchased by a single buyer (man or woman).

Diagram:

Relationship Details:

The Car table should store the buyer ID and buyer type. “Buyer” is a set of model names (men and women), it’s not limited to both, the buyer type is the real name of the model.

Eloquent model:

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(); }}Copy the code

Database migration:

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""buyer_type"
});
Copy the code

Storage records:

// Establish a connection between the buyer (man/woman) and the car.$man->cars()->saveMany([
   $car1.$car2,]);$woman->cars()->saveMany([
   $car1.$car2,]); // Or use the save() function for individual models.$man->cars()->save($car);
$woman->cars()->save($car); // Create a relationship between the car and the buyer (man/woman).$car1->buyer()->associate($man)->save();
$car2->buyer()->associate($woman)->save();
Copy the code

Retrieval records:

// Get the buyer's (man/woman) car$men->cars
$women->cars // Get the buyer of this car (man/woman)$car->buyer
Copy the code

Many-to-many association

Examples:

In this example, we have two models (Driver and Car), and three tables (drivers, an intermediate associated table named CAR_driver).

Business rules:

A driver can drive many cars. A car can be driven by many drivers.

Diagram:

Associated Details:

The association table “car_driver” should hold the driver ID and car ID.

Association model:

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

Database migration:

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

Keep records:

// Create an association between a Driver and a Car.$driver->cars()->attach([
   $car1->id,
   $car2->id, ]); // Or use sync() to prevent duplicate associations.$driver->cars()->sync([
   $car1->id,
   $car2->id, ]); // Create an association between Car and Driver.$car->drivers()->attach([
   $driver1->id,
   $driver2->id, ]); // Or use sync() to prevent duplicate associations.$car->drivers()->sync([
   $driver1->id,
   $driver2->id,
]);
Copy the code

Query records:

// Get Driver Car
$driver->cars
// Get Car Drivers
$car->drivers
Copy the code

Many-to-many-state correlation

Show details:

In this presentation we have three models (Valet, Owner and Car) and four tables (Valets, owners, CARS and drivers).

Business logic:

One surrogate driver can drive many cars one owner can drive many cars one car can be driven by many drivers (surrogate driver and/or owner)

Connection diagram

Association Details:

The middle table “Drivers” should store the driver ID, driver type and vehicle ID. Driving is code for a set of models (Valet and Owner) and does not limit two models. The driver type is the real name of the model.

Eloquent model:

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

Data migration:

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 ') to replace 'driver_id' and 'driver_type'$table->integer('car_id')->unsigned()->index();
    $table->foreign('car_id')->references('id')->on('cars')->onDelete('cascade');
});
Copy the code

Storage records:

// Establish an association between driver (Valet/Owner) and Car$valet->cars()->saveMany([$car1.$car2]);
$owner->cars()->saveMany([$car1.$car2]); // Use the save() method to store a single model$valet->cars()->save($car1);
$owner->cars()->save($car1); // Establish an association between Car and driver (Valet/Owner)$car->valets()->attach([
    $valet1->id,
    $valet2->id,
]);
$car->owners()->attach([
    $owner1->id,
    $owner2->id, ]); // Use sync() to avoid duplicate associations$car->valets()->sync([
    $valet1->id,
    $valet2->id,
]);
$car->owners()->sync([
    $owner1->id,
    $owner2->id,
]);
Copy the code

Obtain records:

// Get the Cars of driver (Valet/Owner)$valet->cars
$owner-> Car drivers (Valet and Owner)$car->owners
$car->valets
Copy the code

For more on modern PHP, visit the Laravel/PHP knowledge community