2017-07-28 71 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路线

相关问题