<?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);
????????});
????}
}
- 2 回答
- 0 關注
- 2048 瀏覽
添加回答
舉報
0/150
提交
取消