gpt4 book ai didi

php - 在多对多关系 laravel 中命名表

转载 作者:IT王子 更新时间:2023-10-29 01:24:11 24 4
gpt4 key购买 nike

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

例如:

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

将表名改为:

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

我的关系有误。

product_feature 怎么了?

最佳答案

Laravel 对数据透视表的命名约定是按字母顺序排列的模型名称,并用下划线分隔。因此,如果一个模型是 Feature,而另一个模型是 Product,则数据透视表将为 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');
}

您可以阅读有关 many to many relationships in the docs 的更多信息.

关于php - 在多对多关系 laravel 中命名表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com