gpt4 book ai didi

php - 使用 Laravel 将数组数据存储在数据库中

转载 作者:行者123 更新时间:2023-11-29 09:38:31 25 4
gpt4 key购买 nike

我想将数组数据存储在数据库中,但在我的数据库中,我只获得表单的第一个输入标签:这是我的 Controller :

public function store(Request $request)
{
$qt = Qt::all();
$Itemname = $request->input('Itemname');
$Quantity = $request->input('Quantity');
$Price = $request->input('Price');
$Tax = $request->input('Tax');
$Total = $request->input('Total');
$GrandTotal = $request->input('GrandTotal');
$data = array('Itemname'=>$Itemname,'Quantity'=>$Quantity,'Price'=>$Price,'Tax'=>$Tax,'Total'=>$Total);
dd($data);
Qt::table('qts')->insert($data);

return redirect()->route('quotes.index');
}

最佳答案

我不确定“一个数据”是什么意思 - 如果您只存储一个字段,那么这种情况就不会发生。按照您的设置方式,它是一个的数据。因此,数据库的预期输出将是保存的单个 Qt 模型。这就是我在基于用户输入单个项目(名称、价格、税费等)的 store() 方法中所期望的。一种形式对应一个新的Qt。我认为您已经为此做好了准备。

但是,Laravel 使新模型的存储变得更加容易。您几乎不需要任何代码,因为看起来您已将传入的表单字段设置为正确匹配 Qt 模型上的字段名称数据库。不过,您可能希望将它们都设为小写以符合约定。

如果表单字段与模型上的数据库字段匹配,您可以删除该方法中的几乎所有内容并将其替换为:

public function store(Request $request)
{
Qt::create($request->all());

return redirect()->route('quotes.index');
}

create 方法将按原样获取 $request 对象,并自动将正确的元素设置到正确的字段(如果它们在模型上设置为可填充)。

编辑:

据我所知,您希望根据表单中传入的许多项目为单个客户制作多行项目。但是,我不知道该信息来自哪里 - 我不知道项目数组位于表单(或 $request 对象)中的位置。这可能是您首先出现错误的原因:我不知道如何循环或查找多个项目,我只看到一个项目进入,这将根据该表单在数据库中生成一行。根据您所说的来自表单的内容,上面的代码是正确的。

但是,根据您在评论中提到的 parameterize() 错误,您可能在某个地方有一个数组导致参数问题,这将帮助您创建多行。您没有显示您的数组是什么,但您提到这些许多项目将附加到单个客户。

这是一种可能的方法。我将根据您所说的内容组成一些变量(一些要循环的数组,存在“客户”对象或类似对象等)

public function store(Request $request)
{
$customer = Customer::find($request->get('customer_id'));
// I don't know how you bring in the customer's id - maybe as a $request item or perhaps through GET?

$newItemsArray = []; // Store the rows of new items here

// Whatever the array of items is, pull it and loop on it to create rows of items:
foreach($request->get('someItemsArray') as $newItem){
// Assuming the name of the array fields match the database field names:
// Assumes $newItem is an associative array
$newItemsArray['Itemname'] = $newItem['Itemname'];
$newItemsArray['Quantity'] = $newItem['Quantity'];
$newItemsArray['Price'] = $newItem['Price'];
$newItemsArray['Tax'] = $newItem['Tax'];
$newItemsArray['Total'] = $newItem['Total'];
}

// Here is where you can create all the rows and attach them at the same time to your customer
$customer->Qts()->createMany($newItemsArray);

return redirect()->route('quotes.index');
}

这将允许创建多行项目并一次性附加到客户。

您需要填写空白 - 如何从表单中发送多行,如何发送正在添加项目的客户,如何处理 GrandTotal(它是数组项目,还是它是从表单传递的单个字段,基于计算)等。但是,这将回答您在 Controller 端的问题,为客户获取多行。

关于php - 使用 Laravel 将数组数据存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com