I have two tables in Laravel, one is the comment
table, and the second is the users
table. In the comment table, I have this type of data.
For this comment table, I want to match the tags
column’s userid in JSON, so how can we join that userid with the user’s table? here is what I tried, but that is not working as expected.
$messages = TopicComment::where('user_id', $currentUserId)
->join("users", "users.id", "=", "users.id")
->(function ($query) {
$query->whereJsonContains('tags.userid', users.id);
})
->
->get()->toArray();
4
Answers
with this package you can create a relation via a json field
https://github.com/staudenmeir/eloquent-json-relations
First, there seem to be a number of errors in your code.
user_id
column in your comments table and so,::where('user_id', $currentUserId)
will not work.join
statement. You’re joining on"users.id","=","users.id"
which is the same column in the same table.function($query)
. Ideally, should be awhere
clause.whereJsonContains
would be:And so, your final result after correcting the changes should look like:
I think the only way to extract is to use json tables.
credit: https://dba.stackexchange.com/questions/306938/extract-json-object-inside-of-an-json-array-then-search-base-on-id
Unfortunately I don’t have json functions on my mysql so the code will probably fail, maybe at least it’ll help get you on the right track.
You can try this way…
eg: