jeudi 30 mai 2019

When do I have to use "many to many", "Has One Through", "Has Many Through" relationship in eloquent?

I'm just curious, when should I use the relation 'many to many', the relation 'has one through', the relation 'has many through'? Because I am sure, these three relations are quite implemented with one to one relations and one to many relationships.

example (taken from laravel documentation):

table :users

id

name

table :roles

id

name

table :RoleUser

id

user_id

role_id

the relation is enough to use one to many, namely 'user' has many 'roleuser' and 'role' has many 'roleusers'.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire