Laravel无法使用Model :: create()和$ model-> save()创建模型

时间:2019-09-30 20:49:36

标签: php laravel eloquent laravel-6

我想播种hero表,但是出现以下错误。

  

参数1传递给Illuminate \ Database \ Query \ Builder :: insertGetId()   必须是给定对象的数组类型,在其中调用

     

E:\ xampp \ htdocs \ cyberpunk \ vendor \ laravel \ framework \   src \ Illuminate \ Database \ Eloquent \ Builder.php在第1350行。

     

异常跟踪:    Illuminate \ Database \ Query \ Builder :: insertGetId(Object(App \ Hero),   “ID”)   ... vendor \ laravel \ framework \ src \ Illuminate \ Database \ Eloquent \ Builder.php:1350

种子

User::find(1)->hero()->create([
    'name' => $faker->userName,
    'level' => $faker->numberBetween(1, 99),
    'strength' => $faker->numberBetween(1, 20),
    'vitality' => $faker->numberBetween(1, 20),
    'stamina' => $faker->numberBetween(1, 20),
    'agility' => $faker->numberBetween(1, 20),
    'perception' => $faker->numberBetween(1, 20),
    'luck' => $faker->numberBetween(1, 20),
]);

我在UserHero之间是一对一的关系。我想通过hero模型创建一个新的user。这种方式也会导致相同的错误。

$hero = new Hero;
$hero->user_id = 1;
...
$hero->save();

用户

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public $appends = ['hashid'];

    public function hero()
    {
        return $this->hasOne(Hero::class);
    }
}

英雄模型

class Hero extends Model
{
    protected $fillable = ['level'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

1 个答案:

答案 0 :(得分:0)

问题是您的$fillable配置。尝试将字段添加到$fillable

class Hero extends Model {

    protected $fillable = ['level', 'client_id', ... ]; // <-- your allowed fields

    public function user() {
        return $this->belongsTo(User::class);
    }
}

现在,请记住,这将需要应用于您的大多数字段。另一种选择是使用相反的$guarded属性。您在此处列出要防止批量分配的字段:

class Hero extends Model {

    protected $guarded = []; // <-- your protected fields go here

    public function user() {
        return $this->belongsTo(User::class);
    }
}

检查文档的related section