PHP 7查询JSON数据类型mysql

时间:2016-07-05 13:39:35

标签: php mysql json laravel-5.2

我有MySQL数据库中的数据,表'user',列'属性',json类型如下:

{"hp": {"base": 10}}

我尝试使用laravel查询数据库json数据,如下所示:

$users = Users::where('attributes->hp->base', 10)->get();

但它返回空结果。因此尝试使用以下内容获取查询:

$users = Users::where('attributes->hp->base', 10)->toSql();

它将查询显示为:

select * from users where attributes->"$.hp.base" = ?

现在当我在MySQL命令行中使用该命令时,它的工作原理

select * from users where attributes->"$.hp.base" = 10

所以,我尝试使用原生的php:

$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = 'select * from users where attributes->"$.hp.base" = 10';
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        var_dump($row);
    }
} else {
    echo "0 results";
}

mysqli_close($conn);

它仍显示0结果。代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

关于选择数据库的评论。所以本机PHP的答案是:

$users = Users::where('attributes->hp->base', DB::raw(10))->get();

现在对于laravel版本,根据https://github.com/laravel/framework/issues/13232需要有DB :: raw()

所以laravel雄辩的版本将是:

/*
CREATE TEMPORARY TABLE REPORTS (DTE DATE, UUID INT);
TRUNCATE TABLE REPORTS;
INSERT INTO  REPORTS VALUES
('2016-07-05' , 192     ),
('2016-07-05' , 192     ),
('2016-07-05' , 192     ),
('2016-07-04' , 230     ),
('2016-07-04' , 230     ),
('2016-07-03' , 227     ),
('2016-07-02' , 227     );

DROP TABLE WARNS;
CREATE TEMPORARY TABLE WARNS (DTE DATE, UUID INT,ACTIVE INT);
INSERT INTO  WARNS VALUES
('2016-07-05'      , 47,0),
('2016-07-05'      , 47,1),
('2016-07-05'      , 47,1),
('2016-07-04'      , 59,0),
('2016-07-03'      , 56,1),
('2016-07-03'      , 56,1),
('2016-07-03'      , 56,1);
*/


SELECT  S.DTE, SUM(S.REPORTS) REPORTS, SUM(S.WARNS) WARNS
FROM         
(
SELECT DTE,1 AS REPORTS, 0 AS WARNS  FROM REPORTS 
UNION ALL
SELECT DTE,0, 1 FROM WARNS WHERE ACTIVE = TRUE 
) S
GROUP BY S.DTE

答案 1 :(得分:-2)

您好请更改您的查询,如下所示

$sql = 'select * from users where attributes->"'.$.hp.base.'" = 10';