mysql - Laravel 使用 whereIn 更新多行

标签 mysql ajax laravel

我通过ajax在字符串中拥有id,

示例:

"1,2"

在我的 Controller 中,我想使用 id => [1,2]whereIn 在一个查询中更新产品的多行。

ajax:

$('#add_product').click(function() { 
   var id = $('#get_value').val();
    $.ajax({
        type: 'POST',
        url: "{{action('ProductController@updateProduct')}}",
        data: {
        id: id
        },
     success: function(data){
          alert("success");
     }
    });
});

Controller :

public function updateProduct(Request $request){
 $test_value = collect($request->id);
 $updateProduct = Product::whereIn('id',$test_value)
                  ->update(['title' => 'My title']);
}

但我在网络中遇到此错误:

SQLSTATE[22007]:无效的日期时间格式:1292 截断的不正确的 DOUBLE 值:'1,2'(SQL:更新“产品”集“标题”=“我的标题”,其中“id”在 (1, 2))

最佳答案

$test_value中,您将获得值"1,2"作为字符串,因此您必须首先使用 explode() 函数将其设为数组(explode() 函数的作用是 here ),

$ids = explode(',',$test_value);

然后传递这个$ids进入你的函数。

public function updateProduct(Request $request){
    $test_value = $request->id;
    $ids = explode(',',$test_value);
    $updateProduct = Product::whereIn('id',$ids)
                  ->update(['title' => 'My title']);
}

关于mysql - Laravel 使用 whereIn 更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752245/

相关文章:

mysql - 如何输出这种层次化的Mysql结构?

MySQL:当引用外部表的列时,在 JOIN 的子查询中使用 WHERE 子句会出现错误

php - 从数据库中选择所有表并在每个表中查询相同的列名

javascript - 如何更改Laravel + Vue.js的动态baseUrl?

php - 如何在 Laravel 4 中使用 rackspace php-opencloud

php - 在 PHP 中连接具有不同 ID 的表字段

javascript - JS Hashchange 事件的 msie 问题

javascript - 使用 AJAX 单击按钮打开 PDF 文件

javascript - 如何从异步调用返回响应?

php - Laravel 5.2 中使用 orWhere 查询范围