foreach使用查询生成器循环的结果在控制器laravel 5.3中

时间:2016-12-01 08:46:36

标签: laravel-5.3

我有宿舍阻止模型如下:

 class Hostel extends Model
      {
       //use Sortable;
       public function block()
       {
         return $this->hasMany('App\Block');
       }
    }

class Block extends Model
{
    // use Sortable;
     public function hostel()
    {
        return $this->belongsTo('App\Hostel');
    }
}

我有变量$gender$capacity从视图通过URL传递。在我的 HostelContoller.php 中,我正在尝试使用列blocks获取所有gender = $gender个旅馆,这些blocks应该包含列capacity = $capacity }。这就是我在HostelContoller.php

中所做的
public function hostels($gender, $capacity)
    {  
        $hostels = Hostel::where('gender', $gender)->get();
        foreach($hostels as $hostel) { 
            $blocks = Block::where('capacity', $capacity)
                            ->where('hostel_id', $hostel->id)
                            ->get();


        }

        # Return the view
        return view('student/booking', ['blocks' => $blocks]);
    }

booking.php我有这个:

@foreach($blocks as $block)
          <tr>

            <td>  {{ $block->hostel->name }}</td>
            <td>  {{ $block ->name}}</td>

这只显示6条记录中的1条记录,而且我不知道我错过了哪条记录。请帮忙!!!

1 个答案:

答案 0 :(得分:0)

每次循环都会重写$ blocks变量。你应该像这样添加块到$ blocks:

public function hostels($gender, $capacity)
            {  
                $hostels = Hostel::where('gender', $gender)->get();
                $blocks = array();
                foreach($hostels as $hostel) { 
                    $blocks[] = Block::where('capacity', $capacity)
                                    ->where('hostel_id', $hostel->id)
                                    ->get();
                }

                # Return the view
                return view('student/booking', ['blocks' => $blocks]);
            }