Laravel技巧集锦(12):使用scope实现用户文章投稿功能

版权声明:http://www.itchuan.net https://blog.csdn.net/sinat_37390744/article/details/88203627

1、Model Topic.php中

   //属于这个专题的所有文章
    public function posts(){
        return $this->belongsToMany(\App\Post::class,'post_topics','topic_id','post_id');
    }

    //专题的文章数目,用于withCount
    public function postTopics(){
        return $this->hasMany(\App\PostTopic::class,'topic_id');
    }

2、Model Post.php中

  //返回该专题下所有文章列表
   public function postTopics(){
        return $this->hasMany(\App\PostTopic::class,'post_id','id');
    }

    //返回属于某个作者的文章
    public  function scopeAuthorBy($query, $user_id){
        return $query->where('user_id',$user_id);
    }

    //不属于某个专题的文章
    public  function scopeTopicNotBy($query, $topic_id){
        return $query->doesntHave('postTopics','and',function ($q) use ($topic_id){
            $q->where('topic_id',$topic_id);
        });
    }

3、Model PostTopic.php 对应数据库 post_topics数据库(id, post_id,  topic_id)关联模型查询

4、TopicController.php中

//专题相关数据
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']));
    }

//文章投稿
    public function submit(Topic $topic){
        $this->validate(\request(),[
            'post_ids' => 'required|array'
        ]);

        $post_ids = \request('post_ids');
        $topic_id = $topic->id;
        foreach ($post_ids as $post_id){
            \App\PostTopic::firstOrCreate(compact('topic_id','post_id'));
        }

        return back();
    }

5、路由

Route::get('/topic/{topic}','TopicController@show');
Route::post('/topic/{topic}/submit','TopicController@submit');

6、视图

//使用post投稿 post_ids数组
<form action="/topic/{{$topic->id}}/submit" method="POST">
   {{csrf_field()}}
     @foreach($myposts666 as $mypost)
         <div class="checkbox">
            <label>
                <input type="checkbox" name="post_ids[]" value="{{$mypost->id}}">
                   {{$mypost->title}}
             </label>
           </div>
      @endforeach                            
     <button type="submit" class="btn btn-default">投稿</button>
</form>

猜你喜欢

转载自blog.csdn.net/sinat_37390744/article/details/88203627
今日推荐