Saturday, April 27, 2024
HomePHPLaravel Desk Relationship Strategies With Instance

Laravel Desk Relationship Strategies With Instance


This Laravel tutorial helps to grasp desk Relationships utilizing Elequonte ORM. We’ll discover laravel desk Relationships utilization and greatest practices with examples.

Understanding Laravel Desk Relationships

There are the next sorts of desk relationships supported by Laravel:

  • One-to-One
  • One-to-Many
  • Many-to-One (Inverse of One-to-Many)
  • Many-to-Many

Let’s assume you have got an “workers” and a “departments” desk, and also you need to carry out a be part of operation utilizing Laravel’s Eloquent ORM. Outline the connection between Worker and Division fashions:

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Worker extends Mannequin
{
    public perform division()
    {
        return $this->belongsTo(Division::class);
    }
}

class Division extends Mannequin
{
    public perform workers()
    {
        return $this->hasMany(Worker::class);
    }
}

One-to-One Relationship

This relationship related every report in a single desk with precisely one report in one other desk.

class Worker extends Mannequin
{
    public perform division()
    {
        return $this->hasOne(Division::class);
    }
}

class Division extends Mannequin
{
    public perform worker()
    {
        return $this->belongsTo(Worker::class);
    }
}

One-to-Many Relationship:

A one-to-many relationship signifies that every report in a single desk might be related to a number of information in one other desk.

class Division extends Mannequin
{
    public perform workers()
    {
        return $this->hasMany(Worker::class);
    }
}

class Worker extends Mannequin
{
    public perform division()
    {
        return $this->belongsTo(Division::class);
    }
}

Many-to-Many Relationship:

A many-to-many relationship associates every report in a single desk with a number of information in one other desk, and vice versa.

class Worker extends Mannequin
{
    public perform departments()
    {
        return $this->belongsToMany(Division::class);
    }
}

class Division extends Mannequin
{
    public perform workers()
    {
        return $this->belongsToMany(Worker::class);
    }
}

Staff could belong to a number of departments, and departments could have a number of workers.

Conclusion

The desk relationship strategies present a robust mechanism for managing information associations between database tables. You’ll be able to outline completely different associations between tables and use the facility of Laravel’s Eloquent ORM.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments