【发布时间】:2017-04-15 11:39:57
【问题描述】:
我在向表中输入数据时遇到此错误
class EntryController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function entry(Request $request){
$category = category::create(['cat_name' => $request->input('cat_name')]);
$product= product::create([
'Product_name'=>$request->input('Product_name'),
'Produc_quantity'=>$request->input('Produc_quantity'),
'Product_Desc' =>$request->input('Product_Desc'),
'cat_id'=>$category->cat_id]);
class category extends Model
{
protected $fillable = array('cat_description','cat_name');
public function product()
{
return $this->hasMany(product::class);
}
//
}
这些是我的模型
class product extends Model
{
protected $fillable = array('Product_name','Product_Desc',
'Produc_quantity','sale_price',
'cost_price');
public function category()
{
return $this->belongsTo(category::class);
}
//
}
我已经从产品模型中的 $fillables 中删除了 cat_id,这导致了这个错误,我不明白这一点我检查了很多论坛和问题,但我没有找到答案 这是产品表
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('Product_name');
$table->string('Product_Desc');
$table->integer('sale_price');
$table->integer('cost_price');
$table->integer('Produc_quantity');
$table->integer('cat_id')->unsigned();
$table->foreign('cat_id')->references('cat_id')->on('categories');
$table->timestamps();
这是分类表
Schema::create('categories', function (Blueprint $table) {
$table->increments('cat_id');
$table->string('cat_name');
$table->string('cat_description');
$table->timestamps();
【问题讨论】:
-
这可能是一个错字,但你的第一堂课在你开始第二堂课之前没有结束
} -
cat_id是您数据库中的自增字段吗? -
是的,它是自动增量
-
去掉 $fillable 上的 cat_id,因为它是自动递增的。
-
我从 $fillables 中删除 cat_id 现在我得到了这个 SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: