Laravel修改收集数据 [英] Laravel Modify collection data

查看:335
本文介绍了Laravel修改收集数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Laravel是否有任何助手来修改集合.我需要做的是使用paginate()进行查询,然后检查登录的用户ID是否与发送者或接收者匹配,然后根据该ID将新值添加到输出中:

I wonder if Laravel have any helper to modify a collection. What I need to do is to make a query with paginate() then check if the logged in users ID match the sender or reciever and based on that add a new value to the output:

$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);

现在我想做类似的事情:

Now I want to do something like:

if (  $allMessages->sender_id == $userId ) {
    //add new value to output
    newField = $allMessages->sendername
} else {
    //add new value to output
    newField = $allMessages->receivername
}

然后发送添加了新值的数据

Then send the data with the new value added

return response()->json(['messages' => $allMessages],200);

这可能吗?

推荐答案

为此,最好使用Collection类的内置函数.例如,map功能将是完美的.

You're better off using the Collection class's built-in functions for this. For example, the map function would be perfect.

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;
});

这篇关于Laravel修改收集数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆