laravel 5.2 Call to undefined method Illuminate\\D

2019-09-11 05:19发布

问题:

I am using laravel 5.2 and I am getting this error while creating user.

Call to undefined method Illuminate\Database\Query\Builder::associate()

this is my 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

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

let me know what is wrong with my code.

回答1:

The associate() function is used to update a belongsTo() relationship. Your role() relationship is a hasOne(), thats why the method doesn't exist.

Source



回答2:

I think you can use associate() method to associate role then change your relationship like below:

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!