Laravel填充我的表格(多对多关系)失败

8

我正在使用Laravel构建一个认证系统,其中用户可以拥有不同的角色。我有三个表:usersrolesrole_user

users
+----------------+------------------+------+-----+---------------------+----------------+
| Field          | Type             | Null | Key | Default             | Extra          |
+----------------+------------------+------+-----+---------------------+----------------+
| id             | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| username       | varchar(255)     | NO   |     | NULL                |                |
| name           | varchar(255)     | NO   |     | NULL                |                |
| surname        | varchar(255)     | NO   |     | NULL                |                |
| email          | varchar(255)     | NO   |     | NULL                |                |
| role_id        | int(10) unsigned | NO   | MUL | NULL                |                |
| password       | varchar(255)     | NO   |     | NULL                |                |
| remember_token | varchar(100)     | YES  |     | NULL                |                |
| created_at     | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
| updated_at     | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
+----------------+------------------+------+-----+---------------------+----------------+

roles
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| role  | varchar(255)     | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+

role_user
+---------+------------------+------+-----+---------+----------------+
| Field   | Type             | Null | Key | Default | Extra          |
+---------+------------------+------+-----+---------+----------------+
| id      | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| role_id | int(10) unsigned | NO   | MUL | NULL    |                |
| user_id | int(10) unsigned | NO   | MUL | NULL    |                |
+---------+------------------+------+-----+---------+----------------+

我想要填充我的表格:

class UserTableSeeder extends Seeder
{

    public function run()
    {
        Schema::table('roles')->delete();
        Role::create(array(
            'role'     => 'Superadmin'
        ));
        Role::create(array(
            'role'     => 'Admin'
        ));
        Role::create(array(
            'role'     => 'User'
        ));

        Schema::table('users')->delete();
        User::create(array(
            'name'     => 'John',
            'surname'     => 'Svensson',
            'username' => 'John_superadmin',
            'email'    => 'john.svensson@gmail.com',
            'role_id'   => 1,
            'password' => Hash::make('1234'),
        ));
        User::create(array(
            'name'     => 'Carl',
            'surname'     => 'Svensson',
            'username' => 'Calle S',
            'email'    => 'carl.svensson@gmail.com',
            'role_id'   => 2,
            'password' => Hash::make('1111'),
        ));
    }

}

针对我的问题:我如何填充role_user表格?我需要一个相应的模型吗?基于现有的用户和角色表,我已经拥有了User和Role模型。

class Role extends Eloquent{

    public function users()
    {
        return $this->belongsToMany('User');
    }

}

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function roles()
    {
        return $this->belongsToMany('Role');
    }
}

当我尝试进行种子操作时,出现的失败信息如下所示:
Argument 2 passed to Illuminate\Database\Schema\Builder::table() must be an instance of Closure, none given
3个回答

6

您的代码存在两个问题。首先,您的错误是由以下原因引起的:

Schema::table('roles')->delete();

Schema 类仅用于架构生成器,此时已经完成了。您不需要在此处使用 Schema 类。而是应该使用 DB 类。

DB::table('roles')->delete();

下一个问题是,在您的代码中,您实际上没有分配角色。您用户表中的`role_id`是无意义的,因为您应该使用一个交叉表来分配角色。
在您的用户表中,`role_id`是一对多关系,而不是像交叉表那样是多对多关系。
要将John分配为超级管理员角色:
// Create the role
$superadmin = Role::create(array(
    'role'     => 'Superadmin'
));


// Create the user
$user = User::create(array(
    'name'     => 'John',
    'surname'     => 'Svensson',
    'username' => 'John_superadmin',
    'email'    => 'john.svensson@gmail.com',
    'password' => Hash::make('1234'),
));

// Assign roles using one of several methods:

// Syncing
$user->roles()->sync([$superadmin->id]);

// or attaching
$user->roles()->attach($superadmin->id);

// or save
$user->roles()->save($superadmin);

你是对的。既然只是一个数据透视表,我想我不需要为此建立一个模型?而且我想我应该只在用户模型中指定belongsToMany关系。 - Bullfinch
你不需要为数据透视表创建一个模型。如果你想让用户拥有多个角色,那么请继续使用数据透视表,并且删除用户表中的 role_id 字段。 - Jake Wilson
你的用户表中的role_id字段应该是一对多关系,而不是像透视表那样是多对多关系。你是不是想说多对多关系? - Gaboik1

2

你需要更正 Schema::tableDB::table,如先前所建议。

然而,填充中间表最简单、性能最佳的方式是像这样:

$users = User::listst('id');

$roles = Role::lists('id');

$usersRoles = [
   // assign roles to users however you like - manually
];

// or maybe in a foreach look

// then run single insert
DB::table('role_user')->insert($usresRoles);

0

错误信息中已经给出了提示。 Schema::table() 期望的格式应该是这样的:

Schema::table('table_name', function($table)
{
    // actions inside of the closure function
});

你有:

Schema::table('roles')->delete();

你需要的是 DB::table('roles')->delete() 或者 DB::table('roles')->truncate() 函数:
// performs a delete, safe for use with foreign keys
// you can use truncate where you don't have to worry about foreign keys
DB::table('roles')->delete();

有关记录删除的更多信息可以在文档部分找到


这是不正确的。delete()截断表值,这正是OP想要的。drop()dropIfExists()会彻底删除实际表格。在该命令之后,将不再有roles表。而且,delete()本来就是DB类的一部分,而不是Schema(请参见我的答案)。 - Jake Wilson
公正的观点,我假设他在试图删除该表格,无论出于何种原因。我会进行更新。 - Samsquanch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接