How to use a resource collection toArray and DB (without Eloquent)

本小妞迷上赌 提交于 2021-02-11 18:20:01

问题


I have this query (in a repository, without using eloquent) :

    public function getUsersOfASchool($schoolId, $request)
    {

        $query = DB::table('school_users as su')
            ->join('users as u', 'u.id', 'su.user_id')
            ->where('su.school_id', $schoolId);

        $users = $query->paginate();

        return $users;
    }

I have this controller :

try{
        $users = $this->userRepository->getUsersOfASchool($school->id, $request->all());
    } catch(\Exception $e) {
        return response()->json(['message'=>'Bad request '.$e->getMessage()], 400);
    }

    return new UserCollection($users);

And at least , I have this collection :

public function toArray($request)
{
    return parent::toArray($request);
}

I have this error 500:

"message": "Call to undefined method stdClass::toArray()",

I think it is because I use the 'DB' facade instead of Eloquent. So how to work with 'DB' facade and collection ?

Merci


回答1:


Yes, because query builder return a collection with stdClass inside.

And ResourceCollection's method toArray will map the collection, then run the toarray() on stdClass. So error occurs.

However, eloquent builder collection will map the collection, run the toArray() on model's object. And this object has toArray() method.

Here is the source code:

    /**
     * Transform the resource into a JSON array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return $this->collection->map->toArray($request)->all();
    }

So you can rewrite the toArray() method for query builder in your resource:

public function toArray($request)
{
    // return parent::toArray($request);

    $collection = $this->collection;
    if (method_exists($collection->map, 'toArray')) {
        return $collection->map->toArray($request)->all();
    } else {
        // for stdClass
        return json_decode(json_encode($collection, true), true);
    }
}


来源:https://stackoverflow.com/questions/60019662/how-to-use-a-resource-collection-toarray-and-db-without-eloquent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!