代码之家  ›  专栏  ›  技术社区  ›  Nitish Kumar

在后续资源中使用分页会在laravel中引发未定义的属性$id错误

  •  0
  • Nitish Kumar  · 技术社区  · 6 年前

    我正在尝试在 Laravel 5.7 我有一个叫 CompanyBehaviour :

    protected $table = 'company_behaviour';
    
    protected $guarded= [];
    
    public function companies()
    {
        return $this->belongsTo('Noetic\Plugins\Conxn\Models\Company','company_id','id');
    }
    
    public function companyRole()
    {
        return $this->belongsTo('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_role_id', 'id');
    }
    
    public function companySpecialisation()
    {
        return $this->belongsTo('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_specialisation_id', 'id');
    }
    

    我有一个资源文件:

    class CompanyBehaviourResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'company' => $this->company->name,
                'company_role' => $this->companyRole->name,
                'company_specialisation' => $this->companySpecialisation->name,
            ];
        }
    }
    

    获取控制器中的数据时需要使用:

    public function index(Request $request)
    {
    
        return new CompanyBehaviourResource(CompanyBehaviour::whereHas('companies', function ($q) use($request) {
            $q->where('name', 'like', '%'.$request->search.'%');
        })->orderBy('created_at', 'desc')
            ->paginate(20)
        );
    }
    

    但是当我调用这个函数时,我会得到分页错误:

    未定义的属性:照明\pagination\lengthawarepaginator::$id

    轨迹表示:

    class: "Illuminate\Http\Resources\Json\JsonResource"
    file: "D:\~Resource\CompanyBehaviourResource.php"
    function: "__get"
    line: 17
    type: "->"
    

    陈述 'id' => $this->id, 这条线。我已经查阅了 Laravel Resource API 我找不到我做错的地方。帮我解决这个问题。谢谢。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Nikola Kirincic    6 年前

    您的调用返回雄辩的集合,而不是单个结果,因此不保持 $id 财产。 您应该改为调用Collection方法:

    public function index(Request $request)
    {
    
        return new CompanyBehaviourResource::collection(CompanyBehaviour::whereHas('companies', function ($q) use($request) {
            $q->where('name', 'like', '%'.$request->search.'%');
        })->orderBy('created_at', 'desc')
            ->paginate(20)
        );
    }
    
    推荐文章