问题
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