Skip to content
Advertisement

Laravel join tables with JSON field, when some fields have no foreign key

I want to join 2 tables by a foreign key stored in a JSON field. The field can be empty, so i get an error, i can not sem to get rid of.

I have a model Transaction:

JavaScript

the items field is json:

JavaScript

now i want to join these tables for a query:

JavaScript

The problem is, that i have many transaction types, so the items field does not necessarily contain the event_id key, or can even be empty.

The SQL query from Eloquent is:

JavaScript

So for rows with empty items-field i get the error:

JavaScript

Is there a way to alter my join and only select rows, that contain the items->event_id key?

[edit] added SQL raw query

Advertisement

Answer

I got it working…

After the help from Akina (thanks), who mentioned, that all fields have to be filled with at least an empty json object:

JavaScript

I was able to join the tables with:

JavaScript

The '$[0].event_id' part is special to this join, because i have my event_id in an object, and this object is in an array:

JavaScript

(Notice the outer brackets)

Without the outer array it would be easy, and i could have just done it without raw sql, like:

JavaScript

[EDIT] FINAL SOLUTION

You will run into performance problems, when joining by JSON fields. My query took about 160s.

The final solution was to create a generated column event_id from the items row. The MySQL “generated column” is autofilled from its expression and automatically updated by MySQL/MariaDB, when the items field is updated.

JavaScript

The laravel migration for that would be

JavaScript

Now my query only takes 0.2s instead of 160s.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement