资源API中的foreach数据透视表? [英] foreach pivot table in resource api?
本文介绍了资源API中的foreach数据透视表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在帖子和标签表之间有数据透视表post_tag
.
I have pivot table post_tag
between posts and tags table.
我想在资源API中显示属于帖子的标签吗?
I want to show the tags which are belongs to the post in in resource API?
资源文件代码段:
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模型中添加的关系:
Relation added in Post model:
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
文件PostController.php:
File 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模型.您的雄辩关系尚未正确定义:
Try updating the Post model.Your eloquent relation is not properly defined yet :
(假设您的数据透视表"post_tag"包含 post_id 和 tag_id 列)
(Assuming your pivot table 'post_tag' contains post_id and tag_id columns)
public function tags()
{
return $this->belongsToMany(Tag::class,'post_tag')->withPivot(['post_id', 'tag_id'])->withTimestamps();
}
这篇关于资源API中的foreach数据透视表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文