Laravel's pivot table + Pivot table in general

后端 未结 4 1738

What are laravel pivot tables and pivot tables in general? What is this all about?

Recently I made research about Pivot table. I thought I know them and What they are bu

4条回答
  •  梦如初夏
    2021-02-12 21:02

    When learning, focus only the pivot tables concept in Laravel (or eloquent). When I was learning I did not care about the general meaning of pivot table. I focused only on facts in the documentation (https://laravel.com/docs/5.5/eloquent-relationships#many-to-many)

    many-to-many relationships require an additional table.And we can insert other useful data to this table as well. And can be used as a model in the system.

    Example : User and Roles many-to-many relationship = User_roles

    Because of Pivot tables, you can retrieve intermediate table data as a model (like other models in the system).

    Example:

    //get user by id
    $user = App\User::find(1);
    
    //get roles of this user
    foreach ($user->roles as $role) {
    
      //pivot attribute returns a model which represent user_role table
      echo $role->pivot->created_at;
    
    }
    

    NOTE: you can create a class by extending pivot. But you have to implement the correct relationships to make it work. Your code should look somewhat similar to below code.

    class Student extends Model
    {
        /**
         * The users that belong to the role.
         */
        public function Rooms()
        {
            return $this->belongsToMany('App\Room')->using('App\Room_Student');
        }
    }
    
    class Room extends Model
    {
        /**
         * The users that belong to the role.
         */
        public function Students()
        {
            return $this->belongsToMany('App\Student')->using('App\Room_Student');
        }
    }
    
    class Room_Student extends Pivot
    {
        //
    }
    

    I hope this helps.

提交回复
热议问题