我有宿舍和阻止模型如下:
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条记录,而且我不知道我错过了哪条记录。请帮忙!!!
答案 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]);
}