未定义的属性:Illuminate \ Database \ Query \ Builder :: $ sessionId

时间:2019-09-23 14:06:11

标签: php database laravel eloquent orm

这是我的PlayerController,播放器和会话模型和资源。

我想使用输入(来自SessionsTable的sessionId)从具有相同ID(userSession)的会议室中获取用户,并以以下格式返回数组:[{userId:1,userName:stacki,userVote:8}, {...},...]

我已经要求[here] [1]实现这一目标,现在我陷入了这个错误。 为了解决此问题,我必须更改什么?仅仅添加-> first()并不能解决我的问题,我需要多个记录。


namespace App\Http\Controllers;

use App\Player;

use Illuminate\Http\Request;
use App\Http\Resources\Players as PlayerResource;

class PlayerController extends Controller
{
    public function index(Request $request)
    {

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

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

        return PlayerResource::collection($currentPlayers);

    }




    public function create()
    { }


    public function update()
    { }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Player extends Model
{
    protected $fillable = [];

    public $sortable = [
        'userId',
        'userName',
        'userVote'
    ];

    public function sessions()
    {
        return $this->hasMany('App\Session');
    }

    public function players(){
        return $this->belongsToMany('App\Session');
    }

}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Session extends Model
{
    protected $fillable = [];

    public function user(){
        return $this->belongsToMany('App\Player');

    }
    public function creator()
    {
        return $this->hasOne('App\Player', 'userId');
    }
}

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

`


  [1]: https://stackoverflow.com/questions/58062014/display-db-entries-in-json-array-in-controller-laravel-php

1 个答案:

答案 0 :(得分:0)

您的Player类可能会扩展Illuminate\Http\Resources\Json\JsonResource而不是ResourceCollection

这应该可以解决您的问题。

use Illuminate\Http\Resources\Json\JsonResource;

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

希望有帮助。