在控制器的json数组中显示数据库条目(Laravel/PHP) [英] Display DB Entries in json Array in Controller (Laravel / PHP)

查看:80
本文介绍了在控制器的json数组中显示数据库条目(Laravel/PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PlayerController中编写索引函数,因此我的Vue组件能够使用以下格式创建一个数组,其中包含userId,userName,userVote:[{userId:1,userName:Jimmy,userVote:7}, {} ...]

I am trying to write an index function in my PlayerController, so my Vue Component is able to create an array with userId, userName, userVote in this form: [{userId:1, userName:Jimmy,userVote:7},{}...]

我有一个Players Table和Session Table,因为我的Player.userSession和Session.sessionId具有相同的属性,所以我正在使用Laravel的请求来获取此信息,使用具有Session ID的另一个类创建一个变量并获取所有用户是房间的一部分.

I have a Players Table and Session Table, because my Player.userSession and Session.sessionId have the same attribute, I am using Laravel's request to fetch this information, create a variable with the other class with Session's ID and get all user who are part of the room.

所有内容均应保存&&回来了.

Everything should be saved && returned back.

到目前为止,这是我的代码:

This is my code so far:

 public function index(Request $request)
    {


        $room = $request->input('sessionId');

        $currentPlayers = Player::where('userSession', $room)->get();

        $userId = $currentPlayers->userId;
        $userName = $currentPlayers->userName;
        $userVote = $currentPlayers->userVote;


        return json_encode([
        'userId' => $userId,
        'userName' => $userName,
        'userVote' => $userVote]);

    }

但是现在它说:此集合实例上不存在属性[userId]."

But now it says it : "Property [userId] does not exist on this collection instance."

https://pasteboard.co/IyJyUZ0.png https://pasteboard.co/IyJypj5.png

推荐答案

您正试图从集合对象中检索模型属性.因为该集合没有包含userId属性,所以引发了错误.您必须迭代数据才能获取它.

You're trying to retrieve a model property from a collection object. The error is thrown because the collection doesn't cotain a userId property. You have to iterate the data in order to get it.

但这不是您要实现的目标.您只需要这些字段的json响应.因此,首先,您必须更改查询或映射集合才能仅选择这些字段...由于您需要JSON响应,因此实现目标的最简单方法是使用

But this is not what you're trying to achieve. You want a json response with only those fields. So, first of all you have to change your query or to map your collection in order to select only those fields... Since you want a JSON Response, the easiest way to achieve your goal is by using Api resources

因此,您声明资源:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Player extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'userId' => $this->userId,
            'userName' => $this->userName,
            'userVote' => $this->userVote,
        ];
    }
}

并从控制器返回此资源作为集合:

and return this resource as a collection from your controller:

<?php

namespace App\Http\Controllers;

use App\Http\Resources\PlayerResource;
// [...]

public function index(Request $request)
{

    $room = $request->input('sessionId');

    $currentPlayers = Player::where('userSession', $room)->get();

    return PlayerResource::collection($currentPlayers);

}

Laravel会为您完成所有魔术工作,以json格式编码结果.

and Laravel will do all the magic for you encoding the result in a json format.

这篇关于在控制器的json数组中显示数据库条目(Laravel/PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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