[英]Laravel 4 Eloquent: how to select where value is in array?
Suppose I have a Model with db record like this: 假设我有一个具有db记录的模型,如下所示:
row1: id: 1 users:["1","2","3"]
row2: id: 2 users:["3","4","5"]
Users are data formatted from json_encode(array($user_id))
. 用户是从
json_encode(array($user_id))
格式化的数据。 Now I want to retrieve the model if user_id
in users
. 现在,如果
users
有user_id
,我想检索模型。 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
. 因此,如果我的
user_id
为2,我将仅检索第1行,但是如果我的user_id
为3,则我将同时检索row1
和row2
。
I tried something like Model::whereIn('users', $user_id)->get();
我尝试了类似
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. 希望您将用户ID存储在会话中或其他内容中,因此your_id是指分配给您自己的ID。
Model::where('id','!=',your_id)->get();
This would return your all the rows, except the id = your_id 这将返回您的所有行,但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:
但是由于您使用的是json_encode,我们可以假定所有数据的格式都相同,并执行以下操作:
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.
你的情况是通常最好使用数据透视表处理,但当然你不必像其他人说使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.