我在创建新产品时无法添加关键产品。我收到错误,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');
}
产品.php
class 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.php
use App\KeyProduct;
use App\Product;
$factory->define(KeyProduct::class, function (Faker $faker) {
$product = factory(Product::class)->create();
return [
'activation_key' => $product->activation_key,
];
});
HUH函数
慕容708150
喵喔喔