【问题标题】:How to access a model from view without using the foreach loop如何在不使用 foreach 循环的情况下从视图访问模型
【发布时间】:2018-10-23 07:14:26
【问题描述】:

我试图创建一个视图,我可以在其中逐个访问数据,就像我有一个问题模型并希望在单独的页面上显示每个问题,或者至少我想控制每个问题的外观在同一页上。

在我的控制器中,我正在做这样的事情

public funciton ShowQuestion($testID){
   $questions = QuestionS::find($testID); 
   // now I have all the questions of a particular test I provided using $testid
   return view('pages.showQuestion')->with('questions' , $questions) ; 
}

在 showQuestion 视图中我想要一些东西,使用它我可以单独访问表的每个实例(行)。

【问题讨论】:

  • 您能在showQuestion 视图中与我们分享您的代码吗?
  • find() 返回单个对象..不需要循环..
  • @Demonowh。但是一个 testID 有多个问题,因为问题和测试之间是多对一的关系!
  • @aceraven777 @extend('layout.app') ; <div class = "container" > @foreach($questions as question) <h3> {{$question->statement}} </h3> @foreach($questions->choices as $choice) <!-- Each Question contains mulitple choices --> <h5> {{$choice->text}} </h5> @endforeach @endforeach @endforeach 但我希望对每个单独的问题对象具有更大的灵活性

标签: laravel view model eloquent


【解决方案1】:

你应该参考问题ID而不是testID,

试试这个:

    public function ShowQuestion($id){
   $question = Question::find($id); 
   //now you should get particular question with given ID
   return view('pages.showQuestion')->with('question' , $question) ; 
}

【讨论】:

  • 但我不是在寻找一个问题。我想在测试中获得所有问题,然后想单独处理它们。
  • 你可以尝试在一个按钮下运行这个控制器,所以抓住所有问题并用一个按钮引用一个而不返回视图
猜你喜欢
  • 1970-01-01
  • 2018-03-21
  • 2013-02-27
  • 2011-01-15
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 2012-01-31
  • 2015-09-09
相关资源
最近更新 更多