0

Suppose I have a Model with db record like this:

row1: id: 1  users:["1","2","3"] 
row2: id: 2  users:["3","4","5"]

Users are data formatted from json_encode(array($user_id)). Now I want to retrieve the model if user_id in users. So if my user_id is 2, i will retrieve only row 1, but if my user_id is 3, i will retrieve both row1 and row2.

I tried something like Model::whereIn('users', $user_id)->get();, it does not work, any other ways to achieve this Eloquent way?

2 Answers 2

2

Hope you are storing your user id in session or something, so your_id refers to the id assigned to yourself.

Model::where('id','!=',your_id)->get();

This would return your all the rows, except the id = your_id

Sign up to request clarification or add additional context in comments.

2 Comments

I think you misunderstood my question, i'm trying to retrieve the model based on users column, not id column (that id has nothing to do with $user_id, it is the id of the model itself).
Thats not best practice , you must implement pivot table concept. or else retrieve and process.
0

I don't think there's a very Eloquent way of doing this. But since you use json_encode, we can assume that all data is formatted the same way, and do something like this:

Model::where('users', 'like', '%"'.$user_id.'"%')->get();

This should work. Your situation is usually best handled with pivot tables, but of course you don't have to use them like the other guy said.

2 Comments

this approach came in my mind at first time, unfortunately when i have a data like this ['13','14','24'], $user_id = 1 still counts (well, since i realize there's no real way to do this, i already had redesign my table, thanks for the answer)
No, it doesn't. It literally looks for "1", with anything before and after. Your example doesn't contain "1", so it won't find the 13, 14, or 24 in your example array. But I'm glad you found a solution! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.