2017-07-28 12 views
1

私はtagsテーブルと多対多の関係を持ち、tagspivotというピボットテーブルを使用して接続されたpostsテーブルを持っています。私は、次の方法を使用してポストを示しています。共通のタグに基づいて関連記事を取得しますか?

public function showpost($titleslug) { 
    $post = Post::where('titleslug','=',$titleslug)->first(); 
    return view('posts/show', compact('post', $post)); 
} 

が、私はポストのタグを読み込むviewのように:私の質問がある

@foreach($post->tags as $ptags) 
    <li><a href="{{route('showtag', $ptags->titleslug)}}" class="button smallGrey">#{{$ptags->title}}</a></li> 
@endforeach 

、同じタグを持つ記事のリストを取得する方法現在のポストを表示していますか?まったく同じタグである必要はありません。他の投稿には1つまたは2つの共通タグがあります。可能であれば、リストは現在の投稿を表示する最も一般的なタグを持つ投稿によってソートされます。私の悪い英語のため申し訳ありませんすべてを、だ

投稿表:

public function up() { 
     Schema::create('posts', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('title'); 
      $table->text('content'); 
      $table->string('titleslug'); 
      $table->timestamps(); 
     }); 
    } 

タグテーブル:

public function up() { 
     Schema::create('tags', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('title'); 
      $table->string('titleslug'); 
      $table->timestamps(); 
     }); 
    } 

Tagspivotテーブル:Postモデルで

public function up() { 
     Schema::create('tagspivot', function (Blueprint $table) { 
      // Create tabel tagspivot 
      $table->increments('id'); 
      $table->integer('post_id')->nullable()->unsigned()->index(); 
      $table->integer('tag_id')->nullable()->unsigned()->index(); 
      $table->timestamps(); 

      // Set FK tagspivot --- posts 
      $table->foreign('post_id') 
        ->references('id') 
        ->on('posts') 
        ->onDelete('cascade') 
        ->onUpdate('cascade'); 

      // Set FK tagspivot --- tags 
      $table->foreign('tag_id') 
        ->references('id') 
        ->on('tags') 
        ->onDelete('cascade') 
        ->onUpdate('cascade'); 
     }); 
    } 

関係

public function tags() 
    { 
     return $this->belongsToMany('App\Tag', 'tagspivot', 'post_id', 'tag_id')->withTimeStamps(); 
    } 

Tagモデルにおける関係::あなたは、現在の$ titleslugによってすべてのポストを取得したい

public function posts() { 
     return $this->belongsToMany('App\Post', 'tagspivot', 'tag_id', 'post_id'); 
    } 
+0

のでshowtagルートで、あなただけの同じことを持っているすべての記事を読み込みたいですタグは、他のタグに関係なく、私はこの権利を得ていますか? –

+0

いいえ、最も関連性の高い投稿を取得するために現在の投稿を表示している共通のタグを共有している投稿のリストを照会するという意味です。 'showtag'ルートはタグに属する投稿のリストを表示しています@OmarTarek –

+0

Laravelのドキュメント、containsとwhereInメソッドを見てください。 https://laravel.com/docs/5.4/collections –

答えて

0

場合は、必要方法whereHas を使用します。

Post::whereHas('tags', function ($query) use ($titleslug) { 
     $query->where('slug', $titleslug); 
    })->get(); 

このコードはで動作しますあなたの関係を適切に書くならば、 whereHasおよび他の参考になっ関係のメソッドの詳細についてはこれを見て:

Querying Relationship Existence

は、それが正しい解決策を見つけるためにあなたを助けることを願って:)

関連する問題