簡體   English   中英

在雄辯的資源中使用分頁會在Laravel中引發Undefined Property $ id錯誤

[英]Using pagination in Eloquent resource throws Undefined Property $id error in Laravel

我試圖建立一個應用程序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)
    );
}

但是當我打電話給我時,我得到了分頁錯誤:

未定義的屬性:Illuminate \\ 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的文檔, 找不到我做錯的地方。 幫我解決這個問題。 謝謝。

您的呼叫返回的是雄辯的集合,而不是單一的結果,因此不持有$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)
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM