1

我正在尝试构建一个应用程序,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的文档,但找不到我做错的地方。帮我解决这个问题。谢谢。

4

1 回答 1

3

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

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)
    );
}
于 2019-01-02T19:29:14.457 回答