选择HSTORE值为$ value Laravel的位置

时间:2015-08-21 18:59:20

标签: php postgresql laravel hstore

使用查询构建器尝试选择HSTORE键$ type中存在值的行。

我的声明:

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

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

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

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

获取表中具有HSTORE

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

通常应该这样做。在您的情况下,meta_data_fields中的数据是json字符串。如果对表中的所有行执行搜索,则将全选。所以这就是我所做的, 我在模型中创建了一个queryScope 1 - 获取所有数据
2 - 提取meta_data_field并解码它 3 - 循环通过meta_data_field
4 - 仅选择符合条件并构建数组

这是一张表

+----+-------------+------------------------------------+-----------+
| 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
    )

)

希望这次对你有用。

答案 1 :(得分:0)

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

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