【问题标题】:Laravel - Integrity constraint violation when trying to create a productLaravel - 尝试创建产品时违反完整性约束
【发布时间】:2020-12-06 06:50:12
【问题描述】:

我正在尝试在数据库中创建产品,但我只是收到错误消息 - -SQLSTATE[23000]:完整性约束违规:1048 列'product_type_id'不能为空(SQL:插入productsproduct_type_idproduct_namefnamesnamepricepages , updated_at, created_at) 值 (?, test, test, test, 15, 15, 2020-12-05 22:25:41, 2020-12-05 22:25:41)) -

我已经尝试改变控制器,所以它会是这样的

 $input = $request->all();

也尝试过更改post方法但没有成功。

控制器 -

public function store(Request $request)
    {    
        $product = new Product();
        $product->product_type_id = request('producttype');
        $product->product_name = request('title');
        $product->fname = request('fname');
        $product->sname = request('sname');
        $product->price = request('price');
        $product->pages = request('pages');
        
       $product->save();
       return redirect('/product');
    }

模板创建.blade.php

<div class="grid-item">
     <form method="POST" action="{{ url('/product/create') }}">
     @csrf
    <h1>Create a product</h1>
    <select id="producttype" value="producttype" name="Product">
      <option value="1">Book</option>
      <option value="2">CD</option>
      <option value="3">Game</option>
    </select>
    <br />
    <input type="text" id="title" name="title" value="title" placeholder="Title">
    <br />
    <input type="text" id="fname" name="fname" value="fname" placeholder="First Name">
    <br />
    <input type="text" id="sname" name="sname" value="sname" placeholder="Surname / Band">
    <br />
    <input type="text" id="price" name="price" value="price" placeholder="Price">
    <br />
    <input type="text" id="pages" name="pages" value="pages" placeholder="Pages / Playlength / PEGI">
    <br />
    <button type="submit">Add new product</button>
    <form/>
</div>

产品型号

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    
        protected $fillable = [
        'product_type_id',
        'product_name',
        'fname',
        'sname',
        'price',
        'pages',
    ];
    
    public function productType()
    {
        return $this->belongsTo('App\Models\ProductType', 'product_type_id');
    }
    
    public function outOfStock() {
        return false;
    }
}

网络路由

Route::post('/product/create', [ProductController::class, 'store']);

在这个问题上的任何帮助都会令人惊叹,因为我已经被这个错误困住了几个小时。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    根据您的 Laravel 代码,您希望在请求中看到 producttype 并将其设置为 product_type_id 的产品值。

    但您以 HTML 格式将其作为Product 发送。

    只需替换

    <select id="producttype" value="producttype" name="Product">
    

    与:

    <select id="producttype" name="producttype">
    

    :)

    【讨论】:

    • 另外id 属性在您的表单中似乎没用。
    猜你喜欢
    • 2013-07-04
    • 2014-12-18
    • 2019-04-12
    • 1970-01-01
    • 2015-09-03
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多