Laravel 通过用户模型中的 id 获取用户并将它们存储在一个数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32443742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel get users by id in user model and store them in an array
提问by Pastor Durán A.
I'm trying to make a simple "friends" system, by storing each friend id in a single column as a string separated with a comma.
我正在尝试制作一个简单的“朋友”系统,方法是将每个朋友 id 存储在单个列中作为用逗号分隔的字符串。
I want to get the users by id and store them in an array:
我想通过 id 获取用户并将它们存储在一个数组中:
public function getFriends() {
$friendids = explode(',', $this->friends);
$friends = [];
foreach ($friendids as $id) {
$friends[] = User::findOrFail($id);
}
return $friends;
}
So I can do this in my view:
所以我可以这样做:
@foreach ($user->getFriends() as $friend)
<p>Friend ID: {{ $friend->id }}</p>
<p>Friend Username: {{ $friend->username }}</p>
@endforeach
But I think I can't use findOrFail in the user model or what am I doing wrong?
但我想我不能在用户模型中使用 findOrFail 或者我做错了什么?
采纳答案by Amo
I made 2 simple mistakes:
我犯了两个简单的错误:
1) I removed User
object from findOrFail()
when looking for the mistake I made
1)我在寻找我犯的错误时删除了User
对象findOrFail()
2) I had specified user id's (friends) that did not exist in the databse, causing an error
2)我指定了数据库中不存在的用户ID(朋友),导致错误
I also improved the code a bit, by adding an optional parameter to get only x amount of users:
我还对代码进行了一些改进,添加了一个可选参数以仅获取 x 个用户:
// App/User.php
public function getFriends($friends_to_get = null) {
$friendids = explode(',', $this->friends);
$friends = [];
$i = 0;
foreach ($friendids as $id) {
if (is_numeric($id)) {
$friends[] = User::findOrFail($id);
}
if (isset($friends_to_get) && $i < $friends_to_get) {
++$i;
}
if (isset($friends_to_get) && $i == $friends_to_get) {
break;
}
}
return $friends;
}
Now you can do something like this in your view:
现在你可以在你的视图中做这样的事情:
@foreach ($user->getFriends() as $friend)
<p>Friend ID: {{ $friend->id }}</p>
<p>Friend Username: {{ $friend->username }}
@endforeach
Or if you want to get, for example, 6 friends only, you can do: $user->getFriends(6)
或者,例如,如果您只想获得 6 个朋友,则可以执行以下操作: $user->getFriends(6)
In my case, $user is the user of who's profile I'm currently viewing. If you want, you could also get your friends only, by doing Auth::user()->getFriends()
就我而言, $user 是我当前正在查看的个人资料的用户。如果你愿意,你也可以只得到你的朋友,这样做Auth::user()->getFriends()
/Edit: Added is_numeric check in the foreach loop. This way you don't have to worry about first and last element in the column having an extra comma. Since explode adds an extra value to the array, if there's a comma in the end of the friends column. Now you can just add or remove x,
from/to the column every time and not worry about fetching an object, that does not exist.
/编辑:在 foreach 循环中添加了 is_numeric 检查。这样您就不必担心列中的第一个和最后一个元素有一个额外的逗号。由于explode 向数组添加了一个额外的值,如果friends 列的末尾有一个逗号。现在,您x,
每次都可以在列中添加或删除,而不必担心获取不存在的对象。
回答by Pastor Durán A.
to use the method findOrFail ($ id); you should invoke the object type you want to get. example
使用方法 findOrFail($id); 您应该调用您想要获取的对象类型。例子
foreach ($friendids as $id) {
$friends[] = User::findOrFail($id);
}
回答by Amo
Although there's an existing answer, I wanted to provide an alternative solution that I personally feel is a better long-term solution.
虽然有一个现有的答案,但我想提供一个替代解决方案,我个人认为这是一个更好的长期解决方案。
Firstly, saving friends as an comma separated list isn't going to scale very well. It also massively limits the ability for you to do things such as 'friends of friends', and other more complex queries.
首先,将朋友保存为逗号分隔的列表不会很好地扩展。它还极大地限制了您执行“朋友的朋友”和其他更复杂查询等操作的能力。
Really, you should have two tables, users
and friends
.
真的,你应该有两个表,users
和friends
.
User model
用户模型
public function acceptedFriends()
{
return $this->hasMany('App\Friend')->where('accepted', true);
}
public function pendingFriends()
{
return $this->hasMany('App\Friend')->where('accepted', false);
}
Now, when a friend request is rejected, you can simply delete the record in the Friends
table.
现在,当朋友请求被拒绝时,您可以简单地删除Friends
表中的记录。
Loading a user with their friends:
加载一个用户和他们的朋友:
$user = User::find($id)->with('acceptedFriends')->firstOrFail();
Loading a user's friend requests:
加载用户的好友请求:
$users = Friends::where('accepted', false)->where('target_user', $userId)->get();
You might want to also check out https://stackoverflow.com/a/25057320/972370. It's written by someone who is very well known in the Laravel community for advanced Eloquent usage.
您可能还想查看https://stackoverflow.com/a/25057320/972370。它是由在 Laravel 社区中因高级 Eloquent 使用而闻名的人编写的。