在多对多关系 Laravel 中命名表

naming tables in many to many relationships laravel(在多对多关系 Laravel 中命名表)
本文介绍了在多对多关系 Laravel 中命名表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I concerned about auto naming tables in many-to-many Laravel relationship.

例如:

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

当表名改为:

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

我的关系有问题.

product_feature 有什么问题?

推荐答案

Laravel 对数据透视表的命名约定是用蛇形大小写的模型名称按字母顺序用下划线分隔.因此,如果一个模型是 Feature,另一个模型是 Product,那么数据透视表将是 feature_product.

Laravel's naming convention for pivot tables is snake_cased model names in alphabetical order separated by an underscore. So, if one model is Feature, and the other model is Product, the pivot table will be feature_product.

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

You are free to use any table name you want (such as product_feature), but you will then need to specify the name of the pivot table in the relationship. This is done using the second parameter to the belongsToMany() function.

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

// in Feature model
public function products()
{
    return $this->belongsToMany('AppProduct', 'product_feature');
}

您可以在文档中阅读有关多对多关系的更多信息.

You can read more about many to many relationships in the docs.

这篇关于在多对多关系 Laravel 中命名表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

In PHP how can you clear a WSDL cache?(在 PHP 中如何清除 WSDL 缓存?)
failed to open stream: HTTP wrapper does not support writeable connections(无法打开流:HTTP 包装器不支持可写连接)
Stop caching for PHP 5.5.3 in MAMP(在 MAMP 中停止缓存 PHP 5.5.3)
Caching HTTP responses when they are dynamically created by PHP(缓存由 PHP 动态创建的 HTTP 响应)
Memcached vs APC which one should I choose?(Memcached 与 APC 我应该选择哪一个?)
What is causing quot;Unable to allocate memory for poolquot; in PHP?(是什么导致“无法为池分配内存?在 PHP 中?)