45

多対多の Laravel 関係でのテーブルの自動ネーミングが気になりました。

例えば:

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

テーブル名を次のように変更する場合:

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

私は私の関係に誤りがあります。

どうしたのproduct_feature

4

1 に答える 1

102

Laravel のピボット テーブルの命名規則は、アンダースコアで区切られたアルファベット順の snake_cased モデル名です。したがって、一方のモデルがFeatureで、もう一方のモデルが のProduct場合、ピボット テーブルは になりますfeature_product

任意のテーブル名 ( などproduct_feature) を自由に使用できますが、リレーションシップでピボット テーブルの名前を指定する必要があります。これは、belongsToMany()関数の 2 番目のパラメーターを使用して行われます。

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

docs で多対多の関係について詳しく読むことができます。

于 2016-01-20T10:40:10.183 に答える