【发布时间】:2023-01-27 06:06:25
【问题描述】:
我试图在这里找到解决方案,但没有任何效果。我想使用 MealResource 从 TagResource 返回值,因为我有 TagTranslations 表,并且我正在从表中获取带有 TagResource 翻译的数据。
关系正确形成,膳食和标签模型通过 meal_tags 表和 tagtranslations belongsTo Tag::class 连接。
我像这样使用 TagResource:
class TagResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
$translation = $this->translations->where('tag_id', $this->id)->first();
return
[
'id' => $this->id,
'title' => $translation->title,
'slug' => $translation->slug,
];
}
}
和 MealResource 是这样的:
public function toArray($request)
{
$translation = $this->translations->where('meal_id', $this->id)->first();
$category_translation = $this->category->translations->where('category_id', $this->category->id)->first();
return [
'id' => $this->id,
'title' => $translation->title,
'decription' => $translation->description,
'category' => [
'id' => $this->category->id,
'title' => $category_translation->title,
'slug' => $category_translation->slug,
],
'tags' => FILL IN THE BLANK (have used TagResource:collection() and new TagResource()) and didnt work
];
}
【问题讨论】:
-
如果您想在 MealResource 标签中设置 Meal 模型标签,您可以通过 Meal 模型的关系发送
标签: laravel api eloquent resources eloquent-relationship