2017-06-21 26 views
5

我一直在使用Laravel 5.4的口才,並且遇到了問題。使用Laravel的口才在JSON列中搜索

我有一個數據庫表,名爲的帖子,並在那一列名爲template_ids。它在json_encoded格式一樣存儲值:

["1","25","48"] 

現在,我想基於ID的陣列上的過濾器適用於我的查詢:

$id_access = array:3 [ 
    0 => "1" 
    1 => "3" 
    2 => "48" 
] 

我所試圖做的是搜索如果數據庫列中存在$id_access值,則template_ids

我想:

Post::where('accessable_to',1)->whereIn('template_ids', $template_access_array)->paginate(3); 

而且,我想:

Post::where('accessable_to',1)->whereRaw("JSON_CONTAINS(template_ids, ".$template_access.")")->paginate(3); 

已經看到this,但它不是爲我工作。

+0

可能是這樣https://stackoverflow.com/questions/41942374/json-search-in-laravel-eloquent會幫助你。此外,您需要將您的列template_ids的數據類型更改爲mysql中的JSON –

+0

您遇到的任何錯誤? –

+0

@Alankar更多我已經添加了鏈接。我看到這篇文章 –

回答

4

要看到,如果template_ids JSON字段包含「任何」的針陣列的價值觀,你會需要使用多個OR倒是JSON_CONTAINS條件,需要MySQL 5.7:

$ids = ['1', '3', '48']; 

Post::where('accessable_to', 1) 
    ->where(function ($query) use ($ids) { 
     $firstId = array_shift($ids); 

     $query->whereRaw(
      'JSON_CONTAINS(template_ids, \'["' . $firstId . '"]\')' 
     ); 

     foreach ($ids as $id) { 
      $query->orWhereRaw(
       'JSON_CONTAINS(template_ids, \'["' . $id . '"]\')' 
      ); 
     } 

     return $query; 
    }); 

return Post::paginate(3); 

Laravel的查詢生成器將產生類似的查詢:

SELECT * FROM "posts" 
WHERE "accessable_to" = ? AND (
    JSON_CONTAINS(template_ids, '["1"]') OR 
    JSON_CONTAINS(template_ids, '["3"]') OR 
    JSON_CONTAINS(template_ids, '["48"]') 
) 

哪些目標有任何這些ID在他們記錄0 JSON類型的字段。

你可能感興趣,閱讀相關Laravel internals proposal

0

怎麼樣說:

$query = Post::where([]); 

$query->where(function($query, $template_ids){ 
    foreach ($template_ids as $id){ 
    $query->orWhere('searching_field', 'like', '%'.$id.'%'); 
    } 
}); 

$query->get()