gpt4 book ai didi

php - Laravel 修改集合数据

转载 作者:行者123 更新时间:2023-12-03 22:53:18 25 4
gpt4 key购买 nike

我想知道 Laravel 是否有任何帮助来修改集合。
我需要做的是使用 paginate() 进行查询然后检查登录的用户 ID 是否与发送者或接收者匹配,并基于此向输出添加一个新值:

$userId = Auth::guard('api')->user()->user_id;
$allMessages = Conversation::join('users as sender', 'conversations.sender_id', '=', 'sender.user_id')
->join('users as reciver', 'conversations.recipient_id', '=', 'reciver.user_id')
->where('sender_id',$userId)->orWhere('recipient_id',$userId)
->orderBy('last_updated', 'desc')
->select('subject','sender_id','recipient_id', 'sender_unread', 'recipient_unread', 'last_updated', 'reciver.username as receivername', 'sender.username as sendername')
->paginate(20);
现在我想做一些类似的事情:
if ($allMessages->sender_id == $userId) {
// add new value to output
newField = $allMessages->sendername
} else {
// add new value to output
newField = $allMessages->receivername
}
然后发送添加了新值的数据
return response()->json(['messages' => $allMessages], 200);
这可能吗?

最佳答案

为此,您最好使用 Collection 类的内置函数。例如,map功能就完美了。

https://laravel.com/docs/5.3/collections#method-map

$allMessages = $allMessages->map(function ($message, $key) use($userId) {
if ($message->sender_id == $userId) {
$message->display_name = $message->receivername;
} else {
$message->display_name = $message->sendername;
}

return $message;
});

关于php - Laravel 修改集合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com