【问题标题】:Show just the name of collection?只显示集合的名称?
【发布时间】:2020-04-27 09:35:53
【问题描述】:

我在帖子和标签表之间有数据透视表post_tag

我想在资源 API 中显示每个帖子的标签名称。

资源文件代码sn-ps:

public function toArray($request)
{
    return [
        'Name'=> $this->title,
        'Description'=> $this->desc,
        'Image'=> $this->image_path,
        'Posted By'=> $this->user->name,
        'Category Name'=> $this->category->name,
        'Tags' => $this->tags,
    ];
}

在 Post 模型中添加的关系:

public function tags()
{
  return $this->belongsToMany(Tag::class)->withTimestamps();
}

API 的结果之一:

 "Name": "first post",
    "Description": "desc of the post",
    "Image": "https://blog.test/uploads/post/SjvDfC1Zk5UzGO6ViRbjUQTMocwCh0lzEYW1Gufp.jpeg",
    "Posted By": "test",
    "Category Name": "web dev",
    "Tags": [
        {
            "id": 1,
            "name": "HTML",
            "created_at": "2020-01-08 19:19:55",
            "updated_at": "2020-01-08 19:19:55",
            "pivot": {
                "post_id": 1,
                "tag_id": 1,
                "created_at": "2020-01-08 19:21:40",
                "updated_at": "2020-01-08 19:21:40"
            }
        },
        {
            "id": 2,
            "name": "CSS",
            "created_at": "2020-01-08 19:19:55",
            "updated_at": "2020-01-08 19:19:55",
            "pivot": {
                "post_id": 1,
                "tag_id": 2,
                "created_at": "2020-01-08 19:21:40",
                "updated_at": "2020-01-08 19:21:40"
            }
        },

我只需要显示这样的名字:

"Tags" : {
    'HTML',
    'CSS',
    'JS',
 }

【问题讨论】:

    标签: laravel api


    【解决方案1】:

    你必须这样使用

    return [
        'Name'=> $this->title,
        'Description'=> $this->desc,
        'Image'=> $this->image_path,
        'Posted By'=> $this->user->name,
        'Category Name'=> $this->category->name,
        'Tags' => $this->tags->pluck('name')
    ];
    

    【讨论】:

    • 完美运行!但是为什么当我这样写时不起作用( $this->tags>name )?
    • 因为 $this->tags 是 Collection 的实例
    • 最后一件事(我的图片像这样正确吗?)意味着移动应用程序是图片放置网址的最佳做法吗?
    • 我不确定这是最好的方法,但我也像你一样使用图片网址。其他情况你可以使用 base_64
    • github.com/codeareaam/laraarea-transformer。这是我制作的包裹。我会尽快写文档
    猜你喜欢
    • 2019-03-16
    • 2019-11-26
    • 1970-01-01
    • 2019-12-23
    • 2018-01-16
    • 1970-01-01
    • 2015-09-14
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多