【问题标题】:laravel 5.2 Call to undefined method Illuminate\Database\Query\Builder::associate()laravel 5.2 调用未定义的方法 Illuminate\Database\Query\Builder::associate()
【发布时间】: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


【解决方案1】:

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

Source

【讨论】:

    【解决方案2】:

    我认为你可以使用associate() 方法来关联角色,然后像下面这样改变你的关系:

    return $this->hasOne('App\Role');
    

    替换为

    return $this->belongsTo('App\Role');
    

    return $this->belongsTo('App\User');
    

    替换为

    return $this->hasOne('App\User');
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2013-11-21
      • 1970-01-01
      • 2018-10-03
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2014-04-25
      • 2017-10-04
      相关资源
      最近更新 更多