当前,我正在尝试为我的应用程序创建角色,不幸的是,我遇到了一些麻烦。每当我运行php artisan migration --seed时,我都会得到标题中写的错误。老实说,我觉得自己搞砸了一些很简单的事情,例如名字,但是我找不到我的错误。我将不胜感激。
User.php模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
public function roles(){
return $this->belongsToMany('App\Role');
}
}
Run Code Online (Sandbox Code Playgroud)
Role.php模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User');
}
}
Run Code Online (Sandbox Code Playgroud)
用户表:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('username');
$table->string('password');
$table->string('email');
$table->timestamps();
$table->rememberToken();
});
}
Run Code Online (Sandbox Code Playgroud)
角色表:
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description')->nullable()->default(null);
$table->timestamps();
});
}
Run Code Online (Sandbox Code Playgroud)
role_user表
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('role_id');
$table->timestamps();
});
}
Run Code Online (Sandbox Code Playgroud)
RoleTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Role;
class RoleTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$role_user = new Role();
$role_user->name = 'User';
$role_user->description = "Normal User";
$role_user->save();
$role_admin = new Role();
$role_admin->name = 'Admin';
$role_admin->description = "Admin User";
$role_admin->save();
}
}
Run Code Online (Sandbox Code Playgroud)
UserTableSeeder.php
public function run()
{
$role_admin = Role::where('name', 'Admin')->first();
$user = new User();
$user->first_name = 'test';
$user->last_name = 'test';
$user->username = 'Admin';
$user->password = bcrypt('test');
$user->email = 'test@gmail.com';
$user->save();
$user->roles()->attach($role_admin);
}
Run Code Online (Sandbox Code Playgroud)
DatabaseSeeder.php
public function run()
{
$this->call(RoleTableSeeder::class);
$this->call(UserTableSeeder::class);
}
}
Run Code Online (Sandbox Code Playgroud)
如评论中所述:
运行:composer dump-autoload。
如果Composer\Exception\NoSslException抛出异常,您可能需要运行composer config -g -- disable-tls true之前composer dump-autoload。
| 归档时间: |
|
| 查看次数: |
6360 次 |
| 最近记录: |