大佬教程收集整理的这篇文章主要介绍了Laravel 5.8 做个知乎 7 ——话题 多对多的保存(collect方法 with方法等) 传统模式与Repository模式,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
resourcesviewsquestionscreate.blade.@R_262_11161@
<SELEct class="js-example-basic-multiple js-example-data-ajax form-control" name="topics[]" multiple="multiple"> </SELEct>
apphttpControllersQuestionsController.@R_262_11161@
public function store(Storequestionrequest $request@H_262_46@) { //自动过滤掉token值 //$this->validate($request,$rules,$messagE); $topics = $this->normailizeTopic($request->get('topics'@H_262_46@)); $data = $request->@H_262_46@all(); $save =@H_262_46@ [ 'title' =>$data['title'], 'body' =>$data['body'], 'user_id' =>Auth::@H_262_46@id() ]; $rs = Question::create($save@H_262_46@); $rs->topics()->attach($topics@H_262_46@); return redirect()->route('question.show',[$rs->@H_262_46@id]); }
private function normailizeTopic(array $topics@H_262_46@) { //collect 遍历方法 return collect($topics)->map(function ($topic@H_262_46@){ if(is_numeric($topic@H_262_46@)){ Topic::find($topic)->increment('questions_count'@H_262_46@); return (int)$topic@H_262_46@; } $newTopic = Topic::create(['name'=>$topic,'questions_count'=>1@H_262_46@]); return $newTopic->@H_262_46@id; })->@H_262_46@toArray(); }
appQuestion.@R_262_11161@
<?@H_262_46@@R_262_11161@ namespace App; use@H_262_46@ IlluminateDatabaseEloquentModel; class Question extends@H_262_46@ Model { //fillable为白名单,表示该字段可被批量赋值;guarded为黑名单,表示该字段不可被批量赋值。 protected $fillable = ['title','body','user_id'@H_262_46@]; public function@H_262_46@ isHidden() { return $this->is_hidden === 'T'@H_262_46@; } public function@H_262_46@ topics() { //多对多的关系 //belongsToMany如果第二个参数不是question_topic的话 可以通过第二个参数传递自定义表名 return $this->belongsToMany(Topic::class,'question_topic'@H_262_46@) ->@H_262_46@withtimestamps(); } }
<?@H_262_46@@R_262_11161@ namespace App; use@H_262_46@ IlluminateDatabaseEloquentModel; class Topic extends@H_262_46@ Model { // protected $fillable = ['name','questions_count'@H_262_46@]; public function@H_262_46@ questions() { return $this->belongsToMany(Question::class@H_262_46@) ->@H_262_46@withtimestamps(); } }
apphttpControllersQuestionsController.@R_262_11161@
public function show($id@H_262_46@) { // //$question = Question::find($id); $question = Question::where('id',$id)->with('topics')->@H_262_46@first(); return view('questions.show',compact('question'@H_262_46@)); }
resourcesviewsquestionsshow.blade.@R_262_11161@
@H_262_46@ @foreach($question->topics as $topiC) <span class="topic">{{$topic->namE}}</span>@H_262_46@ @endforeach
以上是大佬教程为你收集整理的Laravel 5.8 做个知乎 7 ——话题 多对多的保存(collect方法 with方法等) 传统模式与Repository模式全部内容,希望文章能够帮你解决Laravel 5.8 做个知乎 7 ——话题 多对多的保存(collect方法 with方法等) 传统模式与Repository模式所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。