雄辩地建立多对多关系 [英] Set up many to many relationship in laravel eloquent

查看:70
本文介绍了雄辩地建立多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在laravel雄辩中与职位和类别建立多对多关系的最佳实践是什么?是否为数据透视表创建单独的模型?

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');
}

推荐答案

您需要将关系方法名称更改为Categories()

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-是您的数据透视表,您可以定义是否更改命名约定或其可选.

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

您可以使用detach方法或synch方法再次对其进行更新.

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

        $product->categories()->sync($synch); // new category id's

这篇关于雄辩地建立多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆