资源关系?

问题描述 投票:0回答:2

所以我打算开始使用resources作为我的“API”(vue端点)。所以我开始搜索有关该主题的一些教程,并找到了描述该过程的youtuber。我开始制作自己的API资源。 youtubet简要显示how to use the relations,但问题是我在尝试使用资源中的关系时收到Property [description] does not exist on this collection instance.

目前的设置是:

$stack = Stack::select(['id', 'name', 'subject_id', 'description', 'image'])->where('id', '=', $requestId)->first();
$questions = $stack->load('question.choiceInRandomOrder');

return $questions;

而对于资源它会是这样的(注意choiceInRandomOrde,我也需要这种关系):

return [
   'subject' => $this->subject->name,
   'name' => $this->name,
   'slug' => $this->slug,
   'description' => $this->description,
   'image' => $this->image,
   'questions' => [
       'description' => $this->question->description,
       'is_info' => $this->question->is_info,
       'source' => $this->question->source,
       'image' => $this->question->image,
      ]
   ];
}

为了测试,我在我的路线web.php中设置了以下内容

use App\Stack;
use App\Http\Resources\StackResource;

Route::get('/json', function(){
    $stack = Stack::find(2);
    return new StackResource($stack);
});
laravel laravel-5
2个回答
0
投票

你试图访问name中的subject'subject' => $this->subject->name,但是你没有加载关系。


0
投票

我不知道我是否正确,但我认为它必须与不执行Eloquent调用而不是查询生成器调用(当执行$stack = Stack::select ...时)。如果您可以选择直接在模型类中显示的参数,为什么只选择调用中的某些字段? (见this)。

尝试做一个Eloquent调用(类似Stack::find(1))并测试它。它应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.