douque9982 2016-10-12 08:21
浏览 105

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

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.

  • 写回答

2条回答 默认 最新

  • dtc9222 2016-10-12 08:53
    关注

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

    Source

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100