【发布时间】:2023-03-14 04:45:01
【问题描述】:
我有 4 张桌子:
// Table countries
+----+------+
| Id | Name |
+----+------+
| 1 | USA |
| 2 | GB |
+----+------+
// Table platforms
+----+---------+
| Id | Name |
+----+---------+
| 1 | Windows |
| 2 | Linux |
+----+---------+
// Table users
+----+-------+------------+-------------+
| Id | Name | country_id | platform_id |
+----+-------+------------+-------------+
| 1 | Admin | 1 | 1 |
| 2 | Test | 2 | 1 |
+----+-------+------------+-------------+
// Table posts
+----+-----------+------------+-------------+---------+
| Id | Title | country_id | platform_id | user_id |
+----+-----------+------------+-------------+---------+
| 1 | TestPost1 | 2 | 1 | 1 |
| 2 | TestPost2 | 2 | 2 | null |
+----+-----------+------------+-------------+---------+
数据库应该能够实现以下关系:
- 用户 (N) (N) 平台
- 用户 (N) (N) 国家/地区
- 用户 (0..1) (N) 发帖
- 发布 (N) (N) 国家/地区
- 发布 (N) (1) 平台
所以现在我尝试按照Laravel Eloquent ORM 文档实现这些关系:
// Country.php
public function posts()
{
return $this->belongsToMany('App\Post');
}
public function users()
{
return $this->belongsToMany('App\User');
}
// Platform.php
public function users()
{
return $this->belongsToMany('App\User');
}
public function posts()
{
return $this->belongsToMany('App\Post');
}
// User.php
public function posts()
{
return $this->hasMany('App\Post');
}
public function countries()
{
return $this->hasMany('App\Country');
}
public function platforms()
{
return $this->hasMany('App\Platform');
}
// Post.php
public function countries()
{
return $this->hasMany('App\Country');
}
public function platforms()
{
return $this->hasMany('App\Comment');
}
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
但现在我很困惑,因为我认为在mysql中实现N to N关系的方法是在db中添加第三个表,例如这样:
// Table CountryUserRelations to implement User (N) <-> (N) Country
+----+------------+---------+
| Id | country_id | user_id |
+----+------------+---------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 1 | 2 |
| 4 | 2 | 2 |
+----+------------+---------+
但是 Eloquent ORM 如何处理我的模型中的规则?它会保持 N 到 N 的关系而不必添加关系表吗?还是我遗漏了什么或误解了 Eloquent ORM 关系概念?
【问题讨论】:
-
表应该命名为
country_user。不需要文件。 Laravel 查找由按字母顺序排列的下划线分隔的单数名称。 -
所以我需要手动添加这个
country_user表(而不是 CountryUserRelations )或使用php artisan make:migration create_country_user_table?现在我用php artisan make:model User创建了模型,用php artisan make:migration create_users_table创建了表shemas。如果我使用 Eloquent ORM 语法,关系是否会自动添加到此表中? -
是的,您将使用 migrate 方法制作表格。不,不会自动创建关系。你仍然需要做
$table->integer('user_id')->unsigned()->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade')
标签: php mysql laravel eloquent