雄辩地建立多对多关系

时间:2018-08-14 18:37:09

标签: php laravel

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

这就是我在帖子模型中定义它的方式。

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

3 个答案:

答案 0 :(得分:1)

做到这一点的最佳方法是:

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的官方文档:

https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Non_002dSweave-vignettes

答案 1 :(得分:1)

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

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

}

category_product-是您的数据透视表,您可以定义是否更改命名约定或其可选。

在类别模型中,您可以像打击一样定义它

/**
 * 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

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

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

答案 2 :(得分:1)

要定义此关系,需要三个数据库表:post,category和category_post。 category_post表是从相关模型名称的字母顺序得出的,并且包含category_id和post_id列。