【问题标题】:PHP 7 querying JSON data type mysqlPHP 7 查询 JSON 数据类型 mysql
【发布时间】:2016-11-07 09:11:58
【问题描述】:

我在 MySQL db 中有数据,表 'user',列 'attributes',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 个结果。代码有什么问题?

【问题讨论】:

  • 在哪里使用 myslqi 选择数据库名称??
  • 该死,我忘了在原生 PHP 上输入数据库名称。现在它显示了本机的结果。需要弄清楚为什么 laravel one 不起作用。我试过 Users::all() 它有效

标签: php mysql json laravel-5.2


【解决方案1】:

感谢 Saty 关于选择数据库的评论。所以原生 PHP 的答案是:

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

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

所以 laravel 雄辩的版本将是:

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

【讨论】:

    【解决方案2】:

    您好,请按以下方式更改您的查询

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

    【讨论】:

    • 这甚至不解析为 PHP 代码;它在$. 失败。
    猜你喜欢
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多