我在創(chuàng)建新產(chǎn)品時(shí)無法添加關(guān)鍵產(chǎn)品。我收到錯(cuò)誤,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)) 我不知道為什么,它問我那個(gè)。我試過的:category_id是我要添加到表格中的第一列。如果我輸入->nullable(),category_id我會(huì)得到與表中下一列名稱相同的錯(cuò)誤。這是我的代碼:產(chǎn)品控制器 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');}產(chǎn)品表 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(); });關(guān)鍵產(chǎn)品.php public function products() { return $this->HasOne('App\Product')->withPivot('quantity'); }產(chǎn)品.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函數(shù)
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
在您的 SQL 中,您僅為“activation_key”、“updated_at”和“created_at”列提供了值,因此其他字段必須至少滿足一個(gè)語句:
有一個(gè) AUTO_INCREMENT 選項(xiàng);
有默認(rèn)值;
允許 NULL 值。
您沒有提供足夠的數(shù)據(jù)來完成查詢。

慕容708150
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
$fillable
向您的模型添加更多s Product.php
。通過查看您的遷移,它應(yīng)該如下所示:
protected $fillable = [ 'category_id', 'name', 'image', 'activation_key', 'quantity' ];

喵喔喔
TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
它失敗了,因?yàn)閯?chuàng)建產(chǎn)品時(shí)您沒有在創(chuàng)建時(shí)設(shè)置該 category_id 或名稱。使它們?yōu)?nullable() 或相應(yīng)地更改您的創(chuàng)建方法。
- 3 回答
- 0 關(guān)注
- 189 瀏覽
添加回答
舉報(bào)
0/150
提交
取消