<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Topic; class TopicController extends Controller { public function show(Topic $topic) { //带文章数的专题 $topic = Topic::withCount('postTopics')->find($topic->id); //专题的文章列表,按照创建时间倒叙排列,前10个 $posts = $topic->posts()->orderBy('created_at','desc')->take(10)->get(); //属于我的文章,但是未投稿 $myposts = \App\Post::authorBy(\Auth::id())->topicNotBy($topic->id)->get(); return view('topic/show',compact('topic','posts','myposts')); } }
<?php namespace App; use App\Model; class Topic extends Model { //属于这个专题的所有文章 public function posts() { $this->belongsToMany(\App\Post::class,'post_topics','topic_id','post_id'); } //专题的文章数 public function postTopics() { $this->hasMany(\App\PostTopic::class,'topic_id'); } }
<?php namespace App; use Laravel\Scout\Searchable; use Illuminate\Database\Eloquent\Builder; class Post extends Model { //属于某个作者的文章 public function scopeAuthorBy(Builder $query,$user_id) { return $query->where('user_id',$user_id); } public function postTopics() { return $this->hasMany(\App\PostTopic::class,'post_id','id'); } //不属于某个专题的文章 public function scopeTopicNotBy(Builder $query,$topic_id) { return $query->doesntHave('postTopics','and',function ($q) use ($topic_id){ $q->where('topic_id',$topic_id); }); } }
周彪彪