Nel*_*llo 3 laravel laravel-5.2
我正在我的应用程序中创建一个购买的表。所以我有 2 个表:用户和产品。它是多对多的关系。
我知道我们必须为此创建一个新表。表的命名约定是复数形式的用户和产品。
我们如何称呼这张采购表?user_product 还是 users_products?
另外我想我需要一个模型来做这个正确的吗?如果我确实需要一个模型,这个模型的命名约定应该是 User_Product 吗?
从文档:
如前所述,为了确定关系连接表的表名,Eloquent 将按字母顺序连接两个相关模型名称。但是,您可以随意覆盖此约定。您可以通过向belongsToMany 方法传递第二个参数来实现
在您的情况下,Laravel 假设您的连接表将命名为product_user。不需要额外的模型:
用户名
class User extends Model
{
//...
public function products()
{
return $this->belongsToMany(Product::class);
}
//...
}
Run Code Online (Sandbox Code Playgroud)
产品.php
class Product extends Model
{
//...
public function users()
{
return $this->belongsToMany(User::class);
}
//...
}
Run Code Online (Sandbox Code Playgroud)
你的模式看起来像这样:
用户表迁移
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
//...
});
Run Code Online (Sandbox Code Playgroud)
产品表迁移
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
//...
});
Run Code Online (Sandbox Code Playgroud)
product_user 表迁移
Schema::create('product_user', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('user_id');
//...
});
Run Code Online (Sandbox Code Playgroud)
关于命名约定,我认为这会让你的代码更具可读性,所以你可以按照你喜欢的方式命名它(如果你是新手和学习者,我的观点是最好一开始就避免陷入约定,我还在学习自我)
\n\n无论如何,不需要枢轴模型,除非您只需要一些自定义行为
\n\n我想这会对你有帮助
\n\nclass User extends Model\n{\n /**\n * The products that belong to the shop.\n */\n public function products()\n {\n return $this->belongsToMany(\'App\\Products\');\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n你可以这样做: $user->products或查询$product->users,或两者兼而有之。
现在,通过这样的关系声明 Laravel \xe2\x80\x9cassumes\xe2\x80\x9d 数据透视表名称遵守规则并且是user_product。但是,如果 it\xe2\x80\x99s 实际上不同(例如,it\xe2\x80\x99s 复数),则可以将其作为第二个参数提供:
\n\nreturn $this->belongsToMany(\'App\\Products\', \'products_users\');\nRun Code Online (Sandbox Code Playgroud)\n\n如果您想了解如何管理这些,您可以在以下位置找到更多信息这里找到更多信息
\n| 归档时间: |
|
| 查看次数: |
2779 次 |
| 最近记录: |