Postgresql有一些使用JSON数据的函数和操作。如 postgresql site 中所述,可以将 JSON 数据保存在列中并使用 -> 运算符获取 JSON 数组元素。一切正常 纯 PHP,但我想在 Laravel 框架上使用它,特别是 Eloquent或 Query Builder .
在 Laravel 中是否有针对此功能的标准解决方案?我像下面的代码一样开发了普通的 sql,它可以工作,但我正在寻找更好的解决方案。
$host = env('DB_HOST', 'localhost');
$database = env('DB_DATABASE', 'aaa');
$user = env('DB_USERNAME', '22222');
$pass = env('DB_PASSWORD', '11111');
$table = 'table';
$column = 'json';
$connection = pg_connect("host=$host dbname=$database user=$user password=$pass");
$result = pg_fetch_all(pg_query($connection, "SELECT $column->>'name' FROM \"$table\" "));
最佳答案
从 Laravel 5.3 开始,这是可能的,但仅限于 MySQL。 5.6 版还支持 Postgress。假设您有以下用户,其配置文件为 JSON 数据类型:
"id": 1,
"name": "Mahmood",
"profile": {
"bio": "Lorem ipsum",
"phone": "1234"
}
你可以这样查询:
$phone = DB::table('users')
->where('profile->phone', '1234')
->get();
引用:https://mattstauffer.co/blog/new-json-column-where-and-update-syntax-in-laravel-5-3
关于php - 在 Laravel 中使用 JSON 函数等 Postgres 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746680/