Select 其中 HSTORE 值为 $value Laravel

Select where HSTORE value is $value Laravel

使用查询生成器尝试 select 行,其中存在 HSTORE 键 $type 中的值。

我的 Where 语句:

->where("meta_data_fields->'$type'", 'like', '%'.$query.'%')

不确定我做错了什么。我收到此错误:

Undefined column: 7 ERROR: column "meta_data_fields->'Entity::hstore'" does      not exist

有什么想法吗?

获取 table 中具有 HSTORE

的所有记录
Model::where("meta_data_fields", 'like', '%'.$query.'%')->get();

这通常应该可以解决问题。在您的例子中,meta_data_fields 中的数据是一个 json 字符串。如果对 table 中的所有行执行搜索,将 select 全部。所以这就是我所做的, 我在模型中创建了一个 queryScope
1 - 获取所有数据
2 - 提取 meta_data_field 并解码
3 - 遍历 meta_data_field
4 - select 仅匹配条件并构建数组

这是一个table

+----+-------------+------------------------------------+-----------+
| id | name        | desc                               | vendor_id |
+----+-------------+------------------------------------+-----------+
|  1 | apples      | {"type":"fruit","origin":"mexico"} |         1 |
|  2 | oranges     | {"type":"fruit","origin":"peru"}   |         1 |
|  3 | Peaches     | {"type":"fruit","origin":"mexico"} |         2 |
|  4 | Cherries    | {"type":"fruit","origin":"us"}     |         1 |
|  5 | banans      | {"type":"fruit","origin":"brazil"} |      NULL |
|  6 | Water Melon | {"type":"fruit","origin":"mexico"} |         1 |
+----+-------------+------------------------------------+-----------+

public function scopeItems($name ="mexico"){
    $items = array();
    $data =  Self::get();
    $meta_fields = json_decode($data -> pluck('desc') ,true);
    foreach ($meta_fields as $key => $value) {
        if (isset($value['origin']) && $value['origin'] == $name ){
            $items[$key] = $data[$key] -> toArray();
        }
    }
    return $items;
}    
// output 
Array
(
[0] => Array
    (
        [id] => 1
        [name] => apples
        [desc] => Array
            (
                [type] => fruit
                [origin] => mexico
            )

        [vendor_id] => 1
    )

[2] => Array
    (
        [id] => 3
        [name] => Peaches
        [desc] => Array
            (
                [type] => fruit
                [origin] => mexico
            )

        [vendor_id] => 2
    )

[5] => Array
    (
        [id] => 6
        [name] => Water Melon
        [desc] => Array
            (
                [type] => fruit
                [origin] => mexico
            )

        [vendor_id] => 1
    )

)

希望这一次对你有用。

所以这就是在我的情况下 Laravel。

$result = \DB::select(\DB::raw("SELECT hstore_fields, id from table where lower(hstore_fields->'$type') like lower('%$query%')"));