订阅主题

时间:2016-10-12 10:15:59

标签: php laravel

在我的论坛中,我展示了所有主题。它看起来像这样:

enter image description here

因此,用户可以通过点击红色壁炉进行订阅。

我正在用这个json加载主题:

{
  "forum": {
    "id": 1,
    "slug": "test",
    "name": "test",
    "description": "test",
    "created_at": null,
    "updated_at": null
  },
  "topics": {
    "total": 6,
    "per_page": 5,
    "current_page": 1,
    "last_page": 2,
    "next_page_url": "http://forum.dev/api/forum/test?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 5,
    "data": [
      {
        "id": 1,
        "slug": "1",
        "name": "1",
        "description": "1",
        "forum_id": 1,
        "created_at": null,
        "updated_at": null
      },
      {
        "id": 2,
        "slug": "2",
        "name": "1",
        "description": "1\t",
        "forum_id": 1,
        "created_at": null,
        "updated_at": null
      },
      {
        "id": 3,
        "slug": "1",
        "name": "1",
        "description": "1\t",
        "forum_id": 1,
        "created_at": null,
        "updated_at": null
      },
      {
        "id": 4,
        "slug": "1",
        "name": "1",
        "description": "1",
        "forum_id": 1,
        "created_at": null,
        "updated_at": null
      },
      {
        "id": 5,
        "slug": "1",
        "name": "1",
        "description": "1",
        "forum_id": 1,
        "created_at": null,
        "updated_at": null
      }
    ]
  }
}

我正在回复^这样: $forum->topics()->orderBy('created_at', 'DESC')->paginate(5);

那么如何在每个主题对象上获得订阅值?

所以这样:

 "data": [
          {
            "id": 1,
            "slug": "1",
            "name": "1",
            "description": "1",
            "forum_id": 1,
            "created_at": null,
            "updated_at": null,
            "subscribed": true
          },

我已经在我的topic模型上做了这个:

 /**
     * @return mixed
     */
    public function subscriptions()
    {
        return Topic::subscribedBy(Auth::user())->get();
    }

它正在发挥作用。但是如何将每个主题发送给^。

1 个答案:

答案 0 :(得分:1)

您可以通过创建访问者来添加属性(数据库中不存在)。

public function getSubscriptionsAttribute()
{
    return Topic::subscribedBy(Auth::user())->get();
}

然后将其添加到$append属性。

protected $appends = ['subscriptions'];

如果您使用的是$visible白名单,则可能需要将其添加到该属性中。

Source(一直在底部。)