[英]Laravel. Json column with cast as array are returning as a string when using JOIN in query
Laravel 8. I have two tables(models) ' employees
' and ' positions
'. Laravel 8.我有两个表(模型)“
employees
”和“ positions
”。 In a model ' employees
' I have a casts:在 model '
employees
' 我有一个演员表:
protected $casts = [
'academic_post' => 'array'
];
academic_post
is stored as a JSON. When I`m getting positions, joining them with employees: academic_post
存储为 JSON。当我获得职位时,将他们与员工一起加入:
$employees = DB::table('positions')
->select('employees.*', 'positions.*')
->where('department_tag', '=', $this->department_tag)
->leftJoin('employees', 'positions.email', '=', 'employees.email')
->get();
Problem : as employees
table is used in leftJoin , $employees[0]->academic_post
gives a string, not being casted as an array.问题:由于在leftJoin中使用了
employees
表, $employees[0]->academic_post
给出了一个字符串,而不是被转换为数组。 I know I can make a foreach loop and use json_decode
for each row to make an array, but why array casting is not working in this kind of query?我知道我可以制作一个 foreach 循环并为每一行使用
json_decode
来制作一个数组,但为什么数组转换在这种查询中不起作用? If Im using for example: Employee::find(1);
例如,如果我使用:
Employee::find(1);
- Im getting column academic_post
as array
, as expected . - 正如预期的那样,我将列
academic_post
作为array
。 I just want it to work stright from a query, not using any kind of loop.我只是希望它直接从查询中工作,而不是使用任何类型的循环。 Any suggestions?
有什么建议么?
You can get your json fields using mysql function JSON_EXTRACT
您可以使用 mysql function
JSON_EXTRACT
获取您的 json 字段
assuming your json string is like: {"name": "John", "age": 30}
假设您的 json 字符串如下:
{"name": "John", "age": 30}
then you can get each field like this:然后你可以像这样得到每个字段:
$employees = DB::table('positions')
->select('employees.*',
'positions.*',
DB::raw('JSON_EXTRACT(employees.academic_post, \'$.name\') as name'),
DB::raw('JSON_EXTRACT(employees.academic_post, \'$.age\') as age'),
)
->where('department_tag', '=', $this->department_tag)
->leftJoin('employees', 'positions.email', '=', 'employees.email')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.