2017-11-22 5 views
2

私はこの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とrepalced。

ここでフェッチすると、投稿から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

あなたの目標は正しいものではないと思います。あなたは良いデータベース設計を考えるべきです。

あなたの場合、postusersではありません)にmentionsの関係があるとよいです。その後、上記のユーザーを投稿に添付することができます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のビデオは、お客さま専用です。あなたはプライベートリソースを使って質問するべきではありません。あるいは、それをすべて説明しなければなりません。

+0

本当にありがとうと思います。私はこのソリューションを使用して、関係を設定しています。このような素晴らしいアイデアに感謝します。通知も含めてください! :)偶然にも、上記のようにクエリのデータを補う方法を追加することができます。しかし、解決策を受け入れました。 :) – Blagoh

+1

そのような意味ですか?更新しました。 – nmfzone

+0

ありがとう@nmfzone私は関係にそれらを再編することは間違いなく行く方法だと思います。 – Blagoh