Set up many to many relationship in laravel eloquent

前端 未结 3 735
温柔的废话
温柔的废话 2021-01-27 08:59

What is the best practice to setup many to many relationship with post and categories in laravel eloquent? Do I create a separate model for pivot table?

This is how I de

相关标签:
3条回答
  • 2021-01-27 09:39

    The best way to do this is:

    public function categories(){
       return $this->belongsToMany('App\Models\Categories', 'categories_posts', 'post_id', 'category_id');
    }
    

    And then in your Categories model:

    public function posts(){
           return $this->belongsToMany('App\Models\Posts', 'categories_posts', 'category_id', 'post_id');
        }
    

    belongsToMany() method can receive up to 4 parameters, the first one is the location of your model to link, the second is the name of the pivot table, the third one is the current model foreign key and the fourth one is the other's model foreign key.

    You can also specify extra data on pivot table using the withPivot() method like this for example:

    public function categories(){
           return $this->belongsToMany('App\Models\Categories', 'categories_posts', 'post_id', 'category_id')->withPivot('quantity');
        }
    

    And then for attaching you can do as follows:

    $post = Posts:find(1);
    $post->categories()->attach($category_id, ['quantity' => 2]);
    

    But please, refer to Laravel's official documentation:

    https://laravel.com/docs/5.6/eloquent-relationships

    0 讨论(0)
  • 2021-01-27 09:57

    you need to change the relationship method name to categories()

    /**
     * The categories that belong to the product.
     */
    public function categories()
    {
        return $this->belongsToMany('App\Category', 'category_product');
    
    }
    

    category_product - is your pivot table, you can define if you change the naming convention or its optional.

    In Category model, you can define it like blow

    /**
     * The users that belong to the role.
     */
    public function products()
    {
        return $this->belongsToMany('App\Product', 'category_product');
    }
    

    If you require you can create a model for pivot table, in my case this is how i store data to pivot table (using attach method)

            $product->categories()->attach($category); //list of category id's
    

    And you can update it again using detach method or synch method.

            $product->categories()->sync($synch); // new category id's
    
    0 讨论(0)
  • 2021-01-27 10:02

    To define this relationship, three database tables are needed: post, category, and category_post. The category_post table is derived from the alphabetical order of the related model names, and contains the category_id and post_id columns.

    0 讨论(0)
提交回复
热议问题