在许多关系中命名表格

问题描述 投票:19回答:1

我关注多对多Laravel关系中的自动命名表。

例如:

Schema::create('feature_product', function (Blueprint $table) {

将表名更改为:

Schema::create('product_feature', function (Blueprint $table) {

我的关系有误。

product_feature有什么关系?

php laravel laravel-5 eloquent laravel-migrations
1个回答
45
投票

Laravel对数据透视表的命名约定是按字母顺序用下划线分隔的单个表名。因此,如果一个表是features,而另一个表是products,则数据透视表将是feature_product

您可以自由使用任何所需的表名(例如product_feature),但是您需要在关系中指定数据透视表的名称。这是使用belongsToMany()函数的第二个参数完成的。

// in Product model
public function features()
{
    return $this->belongsToMany('App\Feature', 'product_feature');
}

// in Feature model
public function products()
{
    return $this->belongsToMany('App\Product', 'product_feature');
}
© www.soinside.com 2019 - 2024. All rights reserved.