Laravel 资源api中的foreach透视表?
我在posts和tags表之间有pivot表Laravel 资源api中的foreach透视表?,laravel,api,Laravel,Api,我在posts和tags表之间有pivot表post\u tag 我想在资源API中显示属于post的标记 资源文件代码段: public function toArray($request) { return [ 'Name'=> $this->title, 'Descrption'=> $this->desc, 'Image'=> $this->image, 'Posted By'=&
post\u tag
我想在资源API中显示属于post的标记
资源文件代码段:
public function toArray($request)
{
return [
'Name'=> $this->title,
'Descrption'=> $this->desc,
'Image'=> $this->image,
'Posted By'=> $this->user->name,
'Category Name'=> $this->category->name,
'Tags' => $this->whenPivotLoaded('post_tag', function () {
return $this->tags->name;
}),
];
}
在Post模型中添加的关系:
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
文件PostController.php:
public function index()
{
$posts = PostResource::collection(Post::get());
return $this->apiRespone($posts , 'All Post', null ,200);
}
API的结果之一:
{
"Name": "first post",
"Descrption": "desc of the post",
"Image": "SjvDfC1Zk5UzGO6ViRbjUQTMocwCh0lzEYW1Gufp.jpeg",
"User Name": "test",
"Category Name": "web dev"
},
尝试更新帖子模型。您的雄辩关系尚未正确定义: (假设透视表“post_tag”包含post_id和tag_id列)
。。。当加载了('post_tag'…
并且正在加载标记时
。请尝试whenLoaded()
instead@Spholt同样的结果!任何特定的Post::with('tags')在tinker中工作正常吗?@TamzidOronno的意思是?Post::with('tags')->first()
-您看到了什么样的响应将其放入tinker?相同的结果!没有标记!是的,透视表“post\u tag”包含post\u id和tag\u id列
public function tags()
{
return $this->belongsToMany(Tag::class,'post_tag')->withPivot(['post_id', 'tag_id'])->withTimestamps();
}