首页 > 其他 > 详细

Laravel 5.8 做个知乎 7 ——话题 多对多的保存(collect方法 with方法等) 传统模式与Repository模式

时间:2021-06-29 08:53:43      阅读:10      评论:0      收藏:0      [点我收藏+]

1 传统模式

1.1 模板代码

\resources\views\questions\create.blade.php

<select  class="js-example-basic-multiple js-example-data-ajax form-control" name="topics[]" multiple="multiple">

</select>

1.2 控制器代码

\app\Http\Controllers\QuestionsController.php

    public function store(StoreQuestionRequest $request)
    {
        //自动过滤掉token值
        //$this->validate($request,$rules,$message);
        
        $topics = $this->normailizeTopic($request->get(‘topics‘));
        $data = $request->all();
        $save = [
            ‘title‘     =>$data[‘title‘],
            ‘body‘      =>$data[‘body‘],
            ‘user_id‘   =>Auth::id()
        ];
        $rs = Question::create($save);
    
        $rs->topics()->attach($topics);
        
        return redirect()->route(‘question.show‘,[$rs->id]);
    }
技术分享图片
    private function normailizeTopic(array $topics)
    {
        //collect 遍历方法
        return collect($topics)->map(function ($topic){
            if(is_numeric($topic)){
               Topic::find($topic)->increment(‘questions_count‘);
               return (int)$topic;
            }
            $newTopic = Topic::create([‘name‘=>$topic,‘questions_count‘=>1]);
            return $newTopic->id;
        })->toArray();
    }
View Code

1.3 模型

\app\Question.php

技术分享图片
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    //fillable为白名单,表示该字段可被批量赋值;guarded为黑名单,表示该字段不可被批量赋值。
    protected $fillable = [‘title‘,‘body‘,‘user_id‘];
    
    public function isHidden()
    {
        return $this->is_hidden === ‘T‘;
    }
    
    public function topics()
    {
        //多对多的关系
        //belongsToMany如果第二个参数不是question_topic的话 可以通过第二个参数传递自定义表名
        return $this->belongsToMany(Topic::class,‘question_topic‘)
          ->withTimestamps();
    }
}
View Code

\app\Topic.php

技术分享图片
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Topic extends Model
{
    //
    protected $fillable = [‘name‘,‘questions_count‘];
    
    public function questions()
    {
        return $this->belongsToMany(Question::class)
          ->withTimestamps();
    }
    
}
View Code

1.4 保存后显示

\app\Http\Controllers\QuestionsController.php

    public function show($id)
    {
        //
        //$question = Question::find($id);
        $question = Question::where(‘id‘,$id)->with(‘topics‘)->first();
        return view(‘questions.show‘,compact(‘question‘));
    }

\resources\views\questions\show.blade.php

 @foreach($question->topics as $topic)
       <span class="topic">{{$topic->name}}</span>
 @endforeach

 

Laravel 5.8 做个知乎 7 ——话题 多对多的保存(collect方法 with方法等) 传统模式与Repository模式

原文:https://www.cnblogs.com/polax/p/14948047.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!