Laravel 表格一次性插入

Laravel form insert in one go

我创建了一个包含 10 个以上字段的普通 HTML 表单。其中一个字段是提交按钮(显然没有人想将它存储在数据库中)。我正在尝试使用 Product 模型中的以下语句将数据保存在 table 中:

在控制器中:

$id = Product::saveFormData(Input::all());

模型中:

$id = DB::table('products')->insertGetId($data);

它给我以下错误:

Column not found: 1054 Unknown column 'btncreateproduct' in 'field list' (SQL: insert into products (name, url_key, sku, quantity, price, specialprice, description, preorder, page_title, header_data, custom_json_data, btncreateproduct, category_id) values (abc, aaa, bbb, 11, 2222, 1111, abcasdf, no, asdf, asdf, asdf, Create Product, 2))'

现在,首先,为什么要考虑 btncreateproduct 作为一个字段。我不想在我的模型中指定字段列表,因为我希望此代码可扩展(用户可以添加任意数量的字段)。

其次,值abc、aaa不像'abc'、'aaa'

这意味着目前,它没有将它们视为字符串值。尽管它们在数据库中被定义为varchar

您使用 QueryBuilder DB::table('products')... 而不是模型本身来保存新产品的可能原因是什么?

无论如何你都可以按照

的方式做一些事情
$input = Input::except(['btncreateproduct']);
$newProduct = Product::create($input);
$id = $newProduct->id;

也就是说,您 更好 进行适当的验证和类型转换并手动分配这些值,因为在某些时候 table 架构或表单会更改和中断无论如何你的代码。

关于按钮

之所以你的按钮是你提交的一部分,是因为你输入了属性名称。

参见 here 以供参考。

你可以用这个来测试:

<?php var_dump($_POST); ?>
<form action="index.php" method="post" id="form1">
    <button type="submit" name="test" value="Submit1">Submit A</button>
    <button type="submit" value="Submit2">Submit B</button>
</form>

关于在数据库中创建条目

你试图在你的代码中做的事情被称为 Massive Assignment 并且非常危险和不安全。

所以按照建议,您应该使用 Product::create().
使用您的模型 除了在模型 Product 中,您还必须插入 属性 $fillable

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {
    // this is just an example, modify this part in accord to your needs
    protected $fillable = [`name`, `url_key`, `sku`, `quantity`, `price`, `specialprice`, `description`, `preorder`, `page_title`, `header_data`, `custom_json_data`, `category_id`];

    // other code here 
}