【发布时间】:2017-02-20 23:18:42
【问题描述】:
我使用的是 laravel 5.2,我在创建用户时遇到了这个错误。
调用未定义的方法 Illuminate\Database\Query\Builder::associate()
这是我的 User.php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password', 'role_id'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->hasOne('App\Role');
}
}
我的角色.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = "roles";
protected $fillable = [
'name','description'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
这是我使用的迁移
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles');
$table->rememberToken();
$table->timestamps();
});
}
这是我正在使用的控制器代码
$role = Role::find(1);
$user = new User();
$user->name = "Admin";
$user->email = "email@gmail.com";
$user->password = bcrypt("password");
$user->role()->associate($role);
$user->save();
当我运行这段代码时,我得到 “调用未定义的方法 Illuminate\Database\Query\Builder::associate()” 错误
让我知道我的代码出了什么问题。
【问题讨论】:
-
尝试 $role = App\Role::find(1);而不是 $role = Role::find(1);
标签: php laravel laravel-5 laravel-5.2