简体   繁体   中英

Laravel 4 Eloquent: how to select where value is in array?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM