dongzangchui2072 2019-03-07 11:05
浏览 197
已采纳

Eloquent WHERE IN使用原始查询/胶囊管理器

I want to write this query in eloquent using raw queries :

INSERT INTO table SELECT * FROM other_table WHERE other_table_id IN (1,2,3)

I've tried writing it like this :

use Illuminate\Database\Capsule\Manager as DB;
$insert_db = DB::select("SELECT products_id FROM products WHERE products_id IN (?)", [[265792,265787,265743]])

But this is giving me an empty array as a result.

What is the correct way of writing this using the capsule manager? (I absolutely need to do it using DB::select)

This question is asking the same thing, back in 2013. Back then it was not possible. So did that change today? Can we use WHERE IN (?) in the latest versions of eloquent? Knowing that I NEED to use ? for security, and not concatenate the string or it would be meaningless to use PDO at all.

EDIT :

The question is more about dynamic values. I can't use :

DB::select("SELECT products_id FROM products WHERE products_id IN (?, ?, ?)", [265792,265787,265743]);

Because the array [265792,265787,265743] is being built elsewhere. So imagine the following code

foreach($test as $k => $v) {
    $arr[] = $v['something']
}

DB::select("SELECT products_id FROM products WHERE products_id IN (?)", [[$arr]]);
  • 写回答

2条回答 默认 最新

  • doumiao0498 2019-03-07 11:53
    关注

    A cleaner approach to generate the ?, placeholders is to use str_repeat:

    $in = str_repeat('?,', count($arr) - 1) . '?';
    

    Edit #1

    To handle instances where you have zero items in your array, I came up with the following function:

    function in($arr)
    {
      return count($arr) > 0 ? str_repeat('?,', count($arr) - 1) . '?' : false;
    }
    

    Live Example

    Repl

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)