使用Laravel从JSON数组获取数据库表

时间:2018-09-28 19:46:55

标签: php mysql json laravel

我的数据库中有以下记录,我必须在其中获取包含任何记录的所有记录。

表记录包含: $ record_ids = [“ 123”,“ 234”,“ 111”]

尝试使用Laravel进行以下搜索:

$records = DB::table('records_table')
  ->where('id', $id)
  ->whereRaw('JSON_CONTAINS(record_id, ?)', $record_ids)
  ->pluck('records');

我也尝试了类似的解决方案,例如:

->whereIn('record_id', $record_ids)

我正在使用Laravel 5.5和Mysql。

更新: 当我“手动”将其添加如下时,​​它会起作用:

->whereIn('record_id', ["123","234","111"])

但是当从数据库中获取数组时,它不起作用

2 个答案:

答案 0 :(得分:1)

我认为您想在这里使用

findShort("turns out random test cases are easier than writing out basic ones");

function findShort(s){

  let array = s.split(" ");
  let shortestWord = array[0];
  
  for (i = 0; i < array.length; i++) {
    let str = array[i + 1];
    
    if (shortestWord.length > str.length) {
      shortestWord = str.length;
    }
    
  }
  
  return shortestWord;
}

答案 1 :(得分:1)

类型必须匹配(整数与字符串),并且搜索值必须使用JSON编码:

$search = json_encode(array_map('intval', $record_ids));

$records = DB::table('records_table')
    ->where('id', $id)
    ->whereRaw('JSON_CONTAINS(record_id, ?)', $search)
    ->pluck('records');

在Laravel 5.6中,您可以使用whereJsonContains()

->whereJsonContains('record_id', array_map('intval', $record_ids));