Laravel join two tables on Json Column

十年热恋 提交于 2021-02-04 20:50:47

问题


I have two tables(models), one with a json column that may contain the id on other table. I want to join these two together, how do i chain a laravel join to my query.


回答1:


Apply the JSON logic inside the join query like:

Post::select('posts.id', 'posts.field1','posts.field2','samples.id as sample_id', ..)
        ->join('samples', 'posts.json_col_name.id', '=', 'samples.id')
        ->get();

Make sure that you make no conflict for the query builder while picking columns (use field_name as another_name) when both models have fields with common name.




回答2:


SO it turns out the join wasn't working because the json column was storing the id field as a string and the joined table's id is stored as an integer. Casting the result into an integer fixed this. Let's say table 'a' is the first table that contains a json column with an id on second table which is table 'b'.So I did.

DB::table('a')->join('b','b.id',DB::Raw("CAST(a.data->'$.id' AS UNSIGNED)"))->get();


来源:https://stackoverflow.com/questions/49399356/laravel-join-two-tables-on-json-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!