What is Eloquent ORM Relationship with Example? ,2024

Eloquent ORM (Object-Relational Mapping) is a way to interact with a database in a PHP application. It provides a set of classes that allow you to work with your database records as objects, rather than writing raw SQL queries. One of the key features of Eloquent ORM is the ability to define relationships between database tables.

There are several types of relationships that you can define in Eloquent:

  • One-to-one: This is a relationship where a single model is related to one other model. For example, a User model might have one Profile model, and a Profile model might belong to a single User.
  • One-to-many: This is a relationship where a single model is related to many other models. For example, a Category model might have many Product models, and a Product model might belong to a single Category.
  • Many-to-many: This is a relationship where a model can be related to many other models and vice versa. For example, a Book model might have many Author models, and an Author model might have many Book models.
  • Has-one-through: This is a relationship where a model has a one-to-one relationship through another model. For example, a Country model might have one Capital model through a State model, and a State model might belong to a single Country.

1). One-to-one relationship

In Laravel, a one-to-one relationship is a relationship where a model is related to one other model. Here’s an example of how you might define a one-to-one relationship between a User model and a Profile model in Laravel 9:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

To use the relationship, you can do the following:

$user = User::find(1);

// Get the user's profile
$profile = $user->profile;

// Update the user's profile
$profile->phone_number = '123-456-7890';
$profile->save();

// Get the user that a profile belongs to
$user = $profile->user;

Note that in order for this relationship to work, your users table should have a profile_id column that refers to the id column in the profiles table.

2). One-to-many Relationship

In Laravel, a one-to-many relationship is a relationship where a model is related to many other models. Here’s an example of how you might define a one-to-many relationship between a Category model and a Product model in Laravel 9:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

To use the relationship, you can do the following:

$category = Category::find(1);

// Get all the products in the category
$products = $category->products;

foreach ($products as $product) {
    // Do something with the product
}

// Get the category that a product belongs to
$category = $product->category;

Note that in order for this relationship to work, your products table should have a category_id column that refers to the id column in the categories table.

3). Many-to-many Relationship

In Laravel, a many-to-many relationship is a relationship where a model can be related to many other models and vice versa. Here’s an example of how you might define a many-to-many relationship between a Book model and an Author model in Laravel 9:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    public function authors()
    {
        return $this->belongsToMany(Author::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    public function books()
    {
        return $this->belongsToMany(Book::class);
    }
}

To use the relationship, you can do the following:

$book = Book::find(1);

// Get all the authors of the book
$authors = $book->authors;

foreach ($authors as $author) {
    // Do something with the author
}

// Get all the books written by an author
$author = Author::find(1);
$books = $author->books;

foreach ($books as $book) {
    // Do something with the book
}

Note that in order for this relationship to work, you will need to create a pivot table with columns for the book_id and author_id. You can use a migration to create the pivot table:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBookAuthorTable extends Migration
{
    public function up()
    {
        Schema::create('book_author', function (Blueprint $table) {
            $table->unsignedBigInteger('book_id');
            $table->unsignedBigInteger('author_id');

            $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
            $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('book_author');
    }
}

Then you can run the migration using the Artisan command php artisan migrate.

4). Has-one-through

In Laravel, a has-one-through relationship is a relationship where a model has a one-to-one relationship through another model. Here's an example of how you might define a has-one-through relationship between a Country model, a State model, and a Capital model in Laravel 9:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    public function capital()
    {
        return $this->hasOneThrough(Capital::class, State::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class State extends Model
{
    public function country()
    {
        return $this->belongsTo(Country::class);
    }

    public function capital()
    {
        return $this->hasOne(Capital::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Capital extends Model
{
    public function state()
    {
        return $this->belongsTo(State::class);
    }
}

To use the relationship, you can do the following:

$country = Country::find(1);

// Get the country's capital
$capital = $country->capital;

// Update the country's capital
$capital->name = 'New York City';
$capital->save();

// Get the state that a capital belongs to
$state = $capital->state;

// Get the country that a state belongs to
$country = $state->country;

Note that in order for this relationship to work, your states table should have a country_id column that refers to the id column in the countries table, and your capitals table should have a state_id column that refers to the id column in the states table.

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading