猿问

拉拉维尔等效于用户::所有() 函数

伙计们我有问题。Laravelapi


在我的控制器中,当我使用时,一切都很好,但我需要过滤数据,所以当我使用收集时,它会给我错误。错误是collection$teacher$teachersCall to undefined method Illuminate\\Database\\Query\\Builder::mapInto();


我想要过滤后的数据


    $teachers = DB::table('users')->where('role', '=', 1);

    $teacher = Users::all();

    return UserResource::collection($teachers);

我试过这个


$teachers = DB::table('users')->where('role', '=', 1)->get();

$teachers = DB::table('users')->where('role', '=', 1)->get()->toArray();

所以我需要解决方案


这是我的资源


<?php


namespace App\Http\Resources;


use Illuminate\Http\Resources\Json\JsonResource;


class User extends JsonResource

{

    /**

     * Transform the resource into an array.

     *

     * @param  \Illuminate\Http\Request  $request

     * @return array

     */

    public function toArray($request)

    {

        return parent::toArray($request);

    }

}


不负相思意
浏览 94回答 3
3回答

鸿蒙传说

试试这个$teachers = DB::table('users')->where('role', '=', 1);$teacher = Users::all();return new UserResource($teachers);

12345678_0001

我不知道你的,但在我的环境中,这些代码行工作得很好。尝试使用命令更新您的拉拉维尔。composer update

当年话下

return UserResource::collection(User::where('role', '=', 1)->get());这应该对你有用,你能试试吗?更新您仍然可以将表与 连接,但如果您真的想使用eloquentDB::Table()然后你必须像这样指定你的方法。toArray()&nbsp; &nbsp; public function toArray($request)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // return parent::toArray($request);&nbsp; &nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'role' => $this->role,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'id' => $this->id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'name' => $this->name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'email' => $this->email,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'created_at' => $this->created_at,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'updated_at' => $this->updated_at,&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; }并会给你结果。return UserResource::collection(DB::table('users')->where('role', '=', 1)->get());
随时随地看视频慕课网APP
我要回答