foreach where 循环使用查询生成器导致控制器 laravel 5.3
foreach where loop using query builder results in controller laravel 5.3
我有 Hostel 和 Block 模型如下:
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
应该包含 blocks
列=20=]。这就是我在 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 条记录,我不知道我在哪里遗漏了它。请帮忙!!!
你每次循环都要重写 $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]);
}
我有 Hostel 和 Block 模型如下:
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
应该包含 blocks
列=20=]。这就是我在 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 条记录,我不知道我在哪里遗漏了它。请帮忙!!!
你每次循环都要重写 $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]);
}