【问题标题】:how to add an auto increment field in laravel api resource如何在 laravel api 资源中添加自动增量字段
【发布时间】:2020-04-19 09:16:41
【问题描述】:

我想根据他们的点为我的用户进行排名,我想做的是按点对他们进行排序并为其设置一个排名字段。我正在使用 laravel api 资源,在资源中我想添加一个名为 ranking 和 ++ 的字段,因此按用户从 0 到 n 的顺序排列

   $data = User::with('city')
                    ->withCount('point')
                    ->orderByDesc('points_count')
                    ->get()
        ;
        $data = $data->where('points_count', '!=', 0);
        return UserPointResource::collection($data);

这是我的资源:

 return [
            "id"       => (int)$this->id,
            "fullname" => $this->fullname,
            "city"     => $city ? $city->name,
            "count"    => (int)$this->points_count,
        ];

所以我想在每次显示用户并显示用户排名时将名为排名的资源中的计数字段添加到 ++。谢谢

【问题讨论】:

标签: php mysql laravel


【解决方案1】:

您可以像这样在 User 模型中定义一个函数:

    /**
 * Get the User's Rank.
 * @param int $id
 * @return int
 */
public function getRank($id){

    $collection = User::with('city')
        ->withCount('point')
        ->orderByDesc('points_count')
        ->get();

    $data       = $collection->where('id', $id);

    //using array keys to find user rank
    $value      = $data->keys()->first() + 1;


    return $value;
}

然后在您的 UserResource 中调用该函数,如下所示:

 return [
        "id"       => (int)$this->id,
        "fullname" => $this->fullname,
        "city"     => $city ? $city->name,
        "count"    => (int)$this->points_count,
        "rank"     => $this->getRank((int)$this->id),
    ];

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多