Laravel通过2种不同的模型嵌套foreach

时间:2018-06-25 02:25:28

标签: laravel eloquent

我尝试过 this。问题是,如何从不同模型中获取数据?

  

试图获取非对象的属性(视图:C:\ wamp64 \ www \ zainsurgalt \ resources \ views \ choices \ index.blade.php)

控制器

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get();
$choices = Choice::where('user_id',Auth::id())->pluck('question_number')->toArray();
return view('choices.index',compact('duplicates','choices'));

查看

@foreach ($duplicates as $duplicate)
        <tr>
            <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
            <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
            <td style="text-align: center;">{{ $duplicate->total }}</td>
            <td style="text-align: center;">
                @foreach ($choices as $choice)
                    {{ $choice->question_number }}
                @endforeach
            </td>
            <td>
            <a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
        </tr>
    @endforeach

foreach之前的dd($ choices)个结果

array:34 [▼
0 => 5
1 => 5
2 => 0
3 => 0
4 => 0
...
31 => 0
32 => 0
]

添加了此控制器的完整代码

public function index(Choice $choice){

    $duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get();
    $choices = Choice::where('user_id',Auth::id())->pluck('question_number');
    $user = Choice::where('user_id','=',Auth::id())->first();
    if ($user === null) {
        $too = 0;
        return redirect()->route('choices.create');
    }
    else{
        $too = 1;
        return view('choices.index',compact('too','duplicates','choices'));
    }
}

完整的查看代码

<table align="center" border="1" cellpadding="1" cellspacing="1" style="height:106px; width:100%">
    <thead>
        <tr>
            <th colspan="5" scope="col">
            <h3 style="text-align: center;"><b>Шалгалтын цаг сонголт</b></h3>
            <select style="text-align: center;" name="time" class="form-control"> 
                    <option value="30:01">30 минут</option>
                    <option value="40:01">40 минут</option>
                    <option value="50:01">50 минут</option>
                    <option value="60:01">60 минут</option>
                    <option value="70:01">70 минут</option>
                    <option value="80:01">80 минут</option>
                    <option value="90:01">90 минут</option>
            </select></th>
        </tr>
        <tr>
            <th style="text-align: center;" scope="col">№</th>
            <th style="text-align: center;" scope="col">Нэр</th>
            <th style="text-align: center;" scope="col">Нийт асуултын тоо</th>
            <th style="text-align: center;" scope="col">Асуултын тоо</th>
            <th scope="col"></th>
        </tr>
    </thead>
    <tbody>
    @foreach (array_combine($duplicates->toArray(), $choices->toArray()) as $duplicate => $choice){
        <tr>
            <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
            <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
            <td style="text-align: center;">{{ $duplicate->total }}</td>
            <td style="text-align: center;">{{ $choice->question_number }}</td>
            <td><a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
        </tr>
    @endforeach
    </tbody>
</table>

brwanobr oawnbrnoawbn obrawnor bonb rwanobrwn obrawnobrw aonbanobnaowbonwab onbonawb onrwa onbr awnob rwnobrno rbawnorb noawbnorba nobrwaon​​brwa

5 个答案:

答案 0 :(得分:2)

1个解决方案

您正在刀片文件中使用选择ID,但是在查询中,您没有加载ID 因此需要同时加载id和question_number

$choices = Choice::where('user_id',Auth::id())->get(['id','question_number'])->toArray();

另外,当您使用 toArray()时,您需要更改

发件人 {{ $choice->question_number }}

TO {{ $choice['question_number'] }}

与选择相同,编辑链接href="choices/{{ $choice['id'] }}/edit"

或者只是从查询中删除toArray()

2个解决方案

现在,如果您希望将选择与主题一起加载,并且选择模型中具有主题ID

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get(); // Id for this table is your question number or any realtion between the Question Model and Choice Model
$choices = Choice::where('user_id',Auth::id())->pluck('question_number','topic_id')->toArray();
return view('choices.index',compact('duplicates','choices'));


@foreach ($duplicates as $duplicate)
    <tr>
        <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
        <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
        <td style="text-align: center;">{{ $duplicate->total }}</td>
        <td style="text-align: center;">
             {{ isset($choices[$duplicate->topic->id]) ? $duplicate->topic->id : '' }}
        </td>
        <td>
        <a class="btn btn-default" href="choices/{{ isset($choices[$duplicate->topic->id]) ? $choices[$duplicate->topic->id] : '' }}/edit">Шинэчлэх</a></td>
    </tr>
@endforeach

答案 1 :(得分:1)

尝试替换

$choices = Choice::where('user_id',Auth::id())->pluck('question_number')->toArray();

$choices = Choice::where('user_id',Auth::id())->get(); 就像当您采摘时一样,您不会得到钥匙question_number 并得到错误trying t o get property of undefined

答案 2 :(得分:1)

尝试在视图中的foreach循环外访问$choice->id

您已在控制器中使用 pluck()

因此在您看来,您不能使用$choice->question_number

所以您需要更换控制器     查询,或者您可以在下面使用

@foreach ($duplicates as $duplicate)
  @foreach ($choices as $choice)
  // here only can use like this
      {{ $choice }}
      //{{ $choice->question_number }}
    @endforeach           

// this $choice->id out of foreach loop
<a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td> 
@endforeach

或@Mayuri Pansuriya所说,您需要更改控制器查询,然后才能访问

$choices = Choice::where('user_id',Auth::id())->get();

然后您可以在视图中访问

<td style="text-align: center;">
       @foreach ($choices as $choice)
           {{ $choice->question_number }}
       @endforeach
</td>

答案 3 :(得分:1)

如果您希望两个项目都成为对象,请不要在控制器中使用toArray()。我知道在视图中执行此操作的最好方法是,如果对象的长度相同,则使用array_combine()。

控制器

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get()->toArray();
$choices = Choice::where('user_id',Auth::id())->get()->toArray();
return view('choices.index',compact('duplicates','choices'));

查看

@for($i=0; $i< count($duplicates); $i++){
   <tr>
        <td style="text-align: center;">{{ $duplicates[$i]['topic']['id'] }}</td>
        <td style="text-align: center;">{{ $duplicates[$i]['topic']['title'] }}</td>
        <td style="text-align: center;">{{ $duplicates[$i]['total'] }}</td>
        <td style="text-align: center;">{{ $choices[$i]['question_number'] }}</td>
        <td><a class="btn btn-default" href="choices/{{ $choices[$i]['id'] }}/edit">Шинэчлэх</a></td>
    </tr>
@endfor

您显示的错误是由于尝试使用对象语法访问数组:

{{ $choice->question_number }}

$choices = Choice::where('user_id',Auth::id())->pluck('question_number');

如果这是唯一的问题,那就不要在集合上使用toArray()并将其保留为对象或使用数组语法。

答案 4 :(得分:0)

更好地联接所有这些表并将其保留在单个变量中。然后在控制器方法上使用compact()将联接传递给视图,然后通过保留一个变量进行foreach操作,这使您更干净,更好。