【问题标题】:Laravel can't create model with Model::create() and $model->save()Laravel 无法使用 Model::create() 和 $model->save() 创建模型
【发布时间】:2020-01-30 04:13:21
【问题描述】:

我想为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”) ...供应商\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 之间存在一对一的关系。我想通过user 模型创建一个新的hero。这种方式也会导致同样的错误。

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

【问题讨论】:

  • 你能给我们展示一个用户和英雄模型类吗?
  • 当然,我已经编辑了帖子。
  • 你能发布整个 Seeder 文件吗
  • 尝试将 'user_id'(和所有其他字段)添加到 Hero 模型中的可填充属性中:protected $fillable =[ 'user_id', 'level', ...];

标签: php laravel eloquent laravel-6


【解决方案1】:

问题在于您的 $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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多