[英]laravel 5.2 Call to undefined method Illuminate\Database\Query\Builder::associate()
I am using laravel 5.2 and I am getting this error while creating user. 我正在使用laravel 5.2,创建用户时遇到此错误。
Call to undefined method Illuminate\\Database\\Query\\Builder::associate() 调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: associate()
this is my User.php 这是我的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');
}
}
my role.php 我的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');
}
}
and this is migration I used 这是我使用的迁移
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();
});
}
this is controller code I am using 这是我正在使用的控制器代码
$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();
when I run this code I get "Call to undefined method Illuminate\\Database\\Query\\Builder::associate()" error 当我运行此代码时,出现“调用未定义方法Illuminate \\ Database \\ Query \\ Builder :: associate()”错误
let me know what is wrong with my code. 让我知道我的代码有什么问题。
I think you can use associate()
method to associate role then change your relationship like below: 我认为您可以使用
associate()
方法来关联角色,然后像下面那样更改您的关系:
return $this->hasOne('App\Role');
replace with 用。。。来代替
return $this->belongsTo('App\Role');
and 和
return $this->belongsTo('App\User');
replace with 用。。。来代替
return $this->hasOne('App\User');
Hope this help you well! 希望这对您有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.