为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel:没有默认值 - Faker 的 KeyProduct

Laravel:没有默认值 - Faker 的 KeyProduct

PHP
largeQ 2023-04-21 10:45:45
我在创建新产品时无法添加关键产品。我收到错误,SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`activation_key`, `updated_at`, `created_at`) values (57394cd3-54f8-3e95-a951-e11f029fa0f5, 2020-05-27 17:09:08, 2020-05-27 17:09:08)) 我不知道为什么,它问我那个。我试过的:category_id是我要添加到表格中的第一列。如果我输入->nullable(),category_id我会得到与表中下一列名称相同的错误。这是我的代码:产品控制器  public function store(Request $request)    {        $inputs = $request->except('_token');        $quantity = $inputs['quantity'];        factory(KeyProduct::class, $quantity)->create(); foreach ($inputs as $key => $value) {            $home->$key = $value;        }        $home->image=$path;        $home->save();        return redirect('admin/gamelist');}产品表 Schema::create('products', function (Blueprint $table) {            $table->increments('id');            $table->integer('category_id')->unsigned();            $table->string('name');            $table->string('image')->nullable();            $table->string('activation_key')->nullable();            $table->timestamps();        });KeyProduct_table.php         Schema::create('key_products', function (Blueprint $table) {                        $table->increments('id');             $table->string('activation_key');             $table->timestamps();         });关键产品.php public function products()    {        return $this->HasOne('App\Product')->withPivot('quantity');    }产品.phpclass Product extends Model{    public function categories()    {        return $this->belongsTo('App\Category', 'category_id');    }        public function keyProduct()    {        return $this->HasOne('App\KeyProduct');    }    protected $fillable = ['quantity'];}KeyProductFactory.phpuse App\KeyProduct;use App\Product;$factory->define(KeyProduct::class, function (Faker $faker) {    $product = factory(Product::class)->create();    return [            'activation_key' => $product->activation_key,        ];});
查看完整描述

3 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

在您的 SQL 中,您仅为“activation_key”、“updated_at”和“created_at”列提供了值,因此其他字段必须至少满足一个语句:

  1. 有一个 AUTO_INCREMENT 选项;

  2. 有默认值;

  3. 允许 NULL 值。

您没有提供足够的数据来完成查询。


查看完整回答
反对 回复 2023-04-21
?
慕容708150

TA贡献1831条经验 获得超4个赞

$fillable向您的模型添加更多s Product.php。通过查看您的迁移,它应该如下所示:

protected $fillable = [
    'category_id', 'name', 'image', 'activation_key', 'quantity'
    ];


查看完整回答
反对 回复 2023-04-21
?
喵喔喔

TA贡献1735条经验 获得超5个赞

它失败了,因为创建产品时您没有在创建时设置该 category_id 或名称。使它们为 nullable() 或相应地更改您的创建方法。



查看完整回答
反对 回复 2023-04-21
  • 3 回答
  • 0 关注
  • 107 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信