【发布时间】:2019-01-21 16:33:37
【问题描述】:
在 laravel eloquent 中与帖子和类别建立多对多关系的最佳实践是什么?我要为数据透视表创建一个单独的模型吗?
这就是我在后期模型中定义的方式。
public function category()
{
return $this->belongsToMany('App\Category');
}
【问题讨论】:
在 laravel eloquent 中与帖子和类别建立多对多关系的最佳实践是什么?我要为数据透视表创建一个单独的模型吗?
这就是我在后期模型中定义的方式。
public function category()
{
return $this->belongsToMany('App\Category');
}
【问题讨论】:
需要将关系方法名改为categories()
/**
* The categories that belong to the product.
*/
public function categories()
{
return $this->belongsToMany('App\Category', 'category_product');
}
category_product - 是您的数据透视表,您可以定义是否更改命名约定或其可选。
在Category模型中,你可以像blow一样定义它
/**
* The users that belong to the role.
*/
public function products()
{
return $this->belongsToMany('App\Product', 'category_product');
}
如果您需要,您可以为数据透视表创建模型,在我的情况下,这就是我将数据存储到数据透视表的方式(使用附加方法)
$product->categories()->attach($category); //list of category id's
您可以使用分离方法或同步方法再次更新它。
$product->categories()->sync($synch); // new category id's
【讨论】:
最好的方法是:
public function categories(){
return $this->belongsToMany('App\Models\Categories', 'categories_posts', 'post_id', 'category_id');
}
然后在您的类别模型中:
public function posts(){
return $this->belongsToMany('App\Models\Posts', 'categories_posts', 'category_id', 'post_id');
}
belongsToMany() 方法最多可以接收 4 个参数,第一个是要链接的模型的位置,第二个是数据透视表的名称,第三个是当前模型外键,第四个是对方的模型外键。
您还可以使用withPivot() 方法在数据透视表上指定额外数据,例如:
public function categories(){
return $this->belongsToMany('App\Models\Categories', 'categories_posts', 'post_id', 'category_id')->withPivot('quantity');
}
然后附加您可以执行以下操作:
$post = Posts:find(1);
$post->categories()->attach($category_id, ['quantity' => 2]);
但是请参考 Laravel 的官方文档:
【讨论】:
要定义这种关系,需要三个数据库表:post、category 和 category_post。 category_post 表是根据相关模型名称的字母顺序得出的,包含 category_id 和 post_id 列。
【讨论】: