【发布时间】:2018-02-16 14:25:31
【问题描述】:
我有一个包含三个表的迁移,我有一个问题决定表如何相互连接,我真的是它们的外键所以我想要做什么我有两个角色 1 管理员 - 2 用户我想将其中一个分配给每个用户,因为我只希望管理员用户登录后端仪表板,因为现在我将角色和用户之间的关系设为一个(角色)对多(用户)还有帖子之间的关系并且用户是一对多(帖子),因为帖子仅与一个用户相关,但用户可以有多个帖子,所以我需要你在这里帮助以更好的方式理解这些事情以及何时需要设置表中的外键。
这是我的桌子:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('fullname');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles');
$table->rememberToken();
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('content');
$table->string('image');
$table->timestamps();
});
【问题讨论】:
-
roles 不需要 user_id 列,要让用户发帖,您只需在用户模型中添加一个方法并在其中定义 ->hasMany(class::App\Post) 跨度>
-
谢谢 ahmad 但是没有人会这样做 从角色表中的 user_id 获取帖子我必须通过用户模型完成我也只会在登录时检查用户角色是否用户类型是管理员或不是别的。
标签: php mysql laravel laravel-5