2017-07-28 75 views
1

我有一個posts表,它與tags表有多對多的關係,使用名爲tagspivot的數據透視表連接。我表現出後使用下面的方法:根據通用標籤獲取相關帖子?

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 

我的問題是,如何讓帖子的列表具有相同的標籤目前顯示帖子?它不必是完全相同的標籤,就像其他帖子有一個或兩個通用標籤一樣。如果可能的話,列表按照當前顯示帖子中具有最常見標籤的帖子排序。

這一切,對不起,我的英語不好

帖子表:

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(); 
    } 

在變量模型關係:

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

所以,你只是想加載具有相同的所有帖子標記,而不管他們擁有的其他標記是否正確? –

+0

不,我的意思是查詢與當前顯示帖子共享公共標籤以獲取最相關帖子的帖子列表。 'showtag'路由只顯示屬於標籤的帖子列表@OmarTarek –

+0

我認爲你應該看看Laravel文檔,contains和whereIn方法,我希望這會有所幫助。 https://laravel.com/docs/5.4/collections –

回答

0

如果你想獲得的所有職位由目前的$ titleslug你需要使用whereHas方法:

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

此代碼將工作,如果你寫好你的關係的話。有關whereHas和其他有益的關係更多信息的方法看這個:

Querying Relationship Existence

希望它可以幫助您找到正確的解決方案:)在showtag路線

相關問題