简体   繁体   中英

Set up many to many relationship in laravel eloquent

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 defined it in post model.

public function category()
{
    return $this->belongsToMany('App\Category');
}

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM