我正在创建一个购买表格用于我的应用程序。所以我有两个表:用户表和产品表。它们是多对多的关系。
我知道我们需要为此创建一个新表。表格的命名约定应该使用复数形式,例如users和products。
我们该如何称呼这个购买表?是user_product还是users_products?
另外,我认为我需要一个模型来处理这个问题,对吗?如果确实需要一个模型,那么这个模型的命名约定应该是User_Product吗?
来自文档:
如前所述,为了确定关系连接表的表名,Eloquent将按字母顺序连接两个相关模型名称。 但是,您可以自由覆盖此约定。 您可以通过向belongsToMany方法传递第二个参数来这样做。
在您的情况下,Laravel会假设您的连接表的名称为product_user
,无需额外的模型:
User.php
class User extends Model
{
//...
public function products()
{
return $this->belongsToMany(Product::class);
}
//...
}
Product.php
class Product extends Model
{
//...
public function users()
{
return $this->belongsToMany(User::class);
}
//...
}
你的模式看起来是这样的:
用户表迁移
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
//...
});
产品表迁移
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
//...
});
产品用户表迁移
Schema::create('product_user', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('user_id');
//...
});
class User extends Model
{
/**
* The products that belong to the shop.
*/
public function products()
{
return $this->belongsToMany('App\Products');
}
}
$user->products
或者查询 $product->users
,或者两者都要。
现在,有了这样的关系声明,Laravel“假定”中间表名称遵循规则并为user_product。但是,如果实际上不同(例如,它是复数形式),您可以提供它作为第二个参数:
return $this->belongsToMany('App\Products', 'products_users');
->attach()
和->detach()
方法的例子是$user->products()->attach($product);
,这与此无关。 - Achraf Khouadja