获取帖子中提到的用户

时间:2017-11-22 05:15:41

标签: laravel laravel-5.5

我按照这个Laracast教程 - https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/56 - 来获取体内的“提及”。但是我现在想要获取一个线程的所有数据,所以我想要所有帖子和所有相关用户,特别是提到用户。

我正在抓取所有这样的帖子:

public function get(Thread $thread) {
    return $thread->with(['posts'=>function($query) { return $query->with('user'); }]);
}

这回复给我这样的数据:

{
    "id": 1,
    "posts": [
         {
              "id": 1,
              "user_id": 13,
              "body": "Hi @14 and @15",
              "user": {
                  "id": 13,
                  "name": "Joe"
              }
         },
         {
              "id": 2,
              "user_id": 14,
              "body": "Hi back at you"
              "user": {
                  "id": 14,
                  "name": "Bob"
              }
         }
     ]

}

我们看到我的作者用户就好了。但我也需要mentioend用户。

我们在第一个版本中看到,在商店流程中,我将@string转换为@USER_ID

我在商店里这样做了:

preg_match_all('/\@[^\s\.]+)/', $post->body, $matches);

并使用user_id进行了重复。

现在,在获取时,我想从帖子中提取user_id并将这些user附加到结果数据。这可能吗?

我的目标:

{
    "id": 1,
    "posts": [
         {
              "id": 1,
              "user_id": 13,
              "body": "Hi @14 and @15",
              "users": [
                   {
                       "id": 13,
                       "name": "Joe"
                   },
                   {
                       "id": 14,
                       "name": "Bob"
                   },
                   {
                       "id": 15,
                       "name": "Ryan"
                   }
         },
         {
              "id": 2,
              "user_id": 14,
              "body": "Hi back at you",
         }
     ]

}

有没有办法在每个正文上运行正则表达式并选择提到的用户?

1 个答案:

答案 0 :(得分:1)

我认为你的目标不正确。你应该考虑一个好的数据库设计。

在您的情况下,mentions(不是post)中的users关系很好。然后,您可以将提到的用户附加到帖子mentions。像,

preg_match_all('/\@[^\s\.]+)/', $post->body, $matches);

// get the author of the post
$author = $request->user();

// get all the user account for every @, except the author itself
$mentions = User::where(function ($query) use ($matches) {
    foreach ($matches as $item) {
        $query->orWhere('username', 'LIKE', $item);
    }
})->where('id', '!=', $author->id)->get();

// attach the author to the post
$post->user()->save($author);

// attach $mentions to the post
$post->mentions()->saveMany($mentions);

// notify user were mentioned
Notification::send($mentions, new YouWereMentioned($post));

然后获取帖子,你可以这样做,

public function get(Thread $thread) {
    return $thread->with([
        'posts'=> function($query) {
            return $query->with('user', 'mentions');
        }
    ]);
}

注意。 laracasts视频仅适用于订阅者。您不应该使用私有资源提出问题。或者你必须解释一下。

相关问题