Laravel's pivot table + Pivot table in general

后端 未结 4 1739

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 20:52

    If you know about many-to-many relationships this is common, to handle many-to-many relationships we use intermediate (pivot) table to store relationships of two tables. Ex: consider about “education” and “person” tables which are listed below

    table: person

    |------|-------|-----|
    |  id  | name  | age |
    |------|-------|-----|
    |  1   | Bob   | 30  |
    |  2   | John  | 34  |
    |  3   | Marta | 28  |
    |------|-------|-----|
    

    table: education

    |------|-------|
    |  id  | level |
    |------|-------|
    |  1   | BSc   |
    |  2   | MSc   |
    |  3   | PhD   |
    |------|-------|
    

    Think that Bob has BSc, MSc and John has BSc, MSc, PhD and Marta has BSc, now this is consider as many-to-many relationship and to sort this relationship you need to have intermediate table such as,

    table: person_education

    |------------|--------------|
    |  person_id | education_id |
    |------------|--------------|
    |  1         |    1         |
    |  1         |    2         |
    |  2         |    1         |
    |  2         |    1         |
    |  2         |    3         |
    |  3         |    1         |
    |------------|--------------|
    

    This table mainly stores the primary keys (IDs) of each relationship. This is the basic idea behind the pivot table and when you use larval there are some best practises such as,

    • Name of the pivot table should consist of singular names of both tables, separated by undescore symbole and these names should be arranged in alphabetical order

    Laravel Ex:

    Class Person extends Model {
        public function education ()
        {   
          return $this->belongsToMany('App\Education', 'person_education');
        }
    }
    

    Moreover, you can specify the actual field names of that pivot table, if they are different than default person_id and education _id. Then just add two more parameters – first, the current model field, and then the field of the model being joined

    public function education() { 
      return $this->belongsToMany('App\Products', 'products_shops', 'shops_id', 'products_id'); 
    }
    

提交回复
热议问题