本文介绍了laravel 5.2调用未定义的方法Illuminate \ Database \ Query \ Builder :: associate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel 5.2,并且在创建用户时遇到此错误.

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

调用未定义的方法Illuminate \ Database \ Query \ Builder :: associate()

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

这是我的User.php

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');
}
}

我的role.php

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');
}
}

这是我使用的迁移

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 protected]";
    $user->password = bcrypt("password");
    $user->role()->associate($role);
    $user->save();

当我运行这段代码时,我得到调用未定义的方法Illuminate \ Database \ Query \ Builder :: associate()"错误

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.

推荐答案

associate()函数用于更新belongsTo()关系.您的role()关系是hasOne(),这就是为什么该方法不存在的原因.

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

来源

这篇关于laravel 5.2调用未定义的方法Illuminate \ Database \ Query \ Builder :: associate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 21:16