Laravel修改集合数据

时间:2016-09-28 15:26:48

标签: php laravel mutators

我想知道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);

这可能吗?

4 个答案:

答案 0 :(得分:6)

最好使用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;
});

答案 1 :(得分:1)

通过添加:

解决
foreach ($allMessages as $message) {
        if ($message->sender_id == $userId) {
            $message->display_name = $message->receivername;
        } else {
            $message->display_name = $message->sendername;
        }
      }

答案 2 :(得分:0)

你肯定可以使用 Laravel 的 LengthAwarePaginator

除了集合的总数,您还需要传递需要在每个页面上显示的集合数据片段。

$total_count = $allMessages->count();
$per_page = 2;
$current_page = request()->get('page') ?? 1;
$options = [
    'path' => request()->url(),
    'query' => request()->query(),
];

假设你想要每页 2 个结果,然后先计算偏移量

$offset = ($current_page - 1) * $per_page;

现在对集合进行切片以获取每页数据

$per_page_data = $collection->slice($offset, $per_page);

$paginated_data = new LengthAwarePaginator($per_page_data, $total_count, $per_page, $current_page, $options);

$paginated_data 将只有有限数量的由 $per_page 变量声明的项目。

如果您想要接下来的两段数据,请传递 api_request?page="2" 作为您的网址。

答案 3 :(得分:-1)

由于我不知道您正在使用哪种Laravel版本,因此,在Laravel 5.2中,让我为您提供更智能的处理方法(如果我能正确解决您的问题)。

您可以使用Laravel' LengthAwarePaginatiorAPI Docs)。

在构建查询时不要使用paginate方法,而不是使用简单的get方法来获取简单的集合。

$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')
                               ->get();

现在,您可以根据您的特定条件将额外的项目填充到该集合中。

if ($allMessages->sender_id == $userId ) {
  // add new value to collection
} else {
  // add new value to collection
}

现在使用LengthAwarePaginator将填充的集合转换为分页集合。

$total_count = $allMessages->count();
$limit = 20;
$current_page = request()->get('page');
$options = [
    'path' => request()->url(),
    'query' => request()->query(),
];
$paginated_collection = new LengthAwarePaginator($allMessages, $total_count, $limit, $current_page, $options);

现在可以使用变量$paginated_collection作为响应发送。希望这可以帮助您解决问题。