【问题标题】:naming tables in many to many relationships laravel在多对多关系中命名表 laravel
【发布时间】:2016-04-26 03:29:32
【问题描述】:

我担心 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】:

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的信息。

【讨论】:

  • 您能提供参考吗?
  • @MohammadAliAkbari 我添加了文档链接。还更正了关于模型和表名称的轻微假设。
  • 在sql数据库中以单数格式命名pivot有意义吗?
猜你喜欢
  • 2016-09-21
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 2020-01-09
  • 2016-12-20
相关资源
最近更新 更多