【问题标题】:Im trying to insert many rows at once in my DB but im getting an error [closed]我试图在我的数据库中一次插入多行但我得到一个错误[关闭]
【发布时间】:2021-10-01 23:56:25
【问题描述】:

我尝试使用 Laravel 8 和 axios 在我的 MySQL 数据库中一次插入多行,但我收到此错误

这是我的数据库表,名为 auroracoins

我获取数据的api是这样的

这是我的 axios 调用

       async insertar(history_records) {
            try {
                console.log(history_records)
                const response = await axios
                    .post("/home/insert", history_records.results)
                    .then(response => {
                        console.log("worked")
                        // this.categories.push(this.categoryToAdd);
                    })
                    .catch(error => {
                        console.log(error);
                    });
            } catch (error) {
                this.request_status = error;
                console.log(error);
            }
        },

就是web.php路由

这里是存储功能[![在此处输入图片描述][7]][7]

PD:很抱歉使用图像而不是代码,但我遇到了一些格式问题

    public function store(Request $request)
{
    error_log($request);

    //Create item


    foreach ($request as $history_record) {

        $history = new Auroracoin();
        $history->history_date = $history_record->date;
        $history->rate = $history_record->rate;
    }

    $history->save();

    return $history;
}

【问题讨论】:

  • Sorry for using images instead of code, but im having some formating problems...然后修复格式问题。根据How to Ask,代码图像无用且不受欢迎。如果您需要有关如何显示代码的帮助,请参阅stackoverflow.com/help/formatting。谢谢。

标签: php mysql laravel axios laravel-8


【解决方案1】:

不要直接循环 $request,它是一个 symfony Request 对象。

要循环您发送的数据,请使用

foreach ($request->all() as $history_record) {
    $history = new Auroracoin();
    $history->history_date = $history_record['date'];
    $history->rate = $history_record['rate'];
}

数据作为 json 对象发送的事件,http 中没有这样的事情。您需要以关联数组$history_record['date']

的形式访问它们

$request->all() 返回一个数组,其中包含随请求发送的所有 POST/GET 数据。

【讨论】:

  • 感谢 N69S 完美运行,现在我明白了:D
猜你喜欢
  • 2019-05-09
  • 1970-01-01
  • 2022-01-27
  • 2015-01-14
  • 2021-11-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多