Reputation: 191
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.
Upvotes: 4
Views: 9279
Reputation: 308
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.
Upvotes: 2
Reputation: 191
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();
Upvotes: 2