按与其他模型的关系分组的模型记录
records for the model grouped by the relationship with the other model
我有一个具有一对多关系的模型,我想查看按关系分组的模型的所有记录。
比如我想输出这样的东西:
一个[1]
- 很多[1]
- 很多[2]
- 很多[3]
一个[2]
- 很多[4]
- 很多[5]
- 很多[6]
到目前为止,使用下面给出的代码我可以得到:
一个[1]
- 很多[1]
- 很多[2]
- 很多[3]
一个[2]
- 很多[1]
- 很多[2]
- 很多[3]
型号
class Many extends Model
{
public function ones()
{
return $this->hasOne('App\Models\One');
}
}
class One extends Model
{
public function manys()
{
return $this->hasMany('App\Models\Many');
}
}
控制器
class YeargroupController extends Controller
{
public function index()
{
$one = One::get();
$ones = One::find(1)->manys;
}}
观看次数
</div>@foreach ($ones as $row)
<div class="card-body">{{$row->name}}
<div class="row">@foreach ($one as $row)
{{$row->name}}
</div>@endforeach
</div>
</div> @endforeach
如何访问下一条记录的关系?
class YeargroupController extends Controller
{
public function index()
{
return view(..., [
// get all the 'ones' with their relationship loaded
'ones' => One::with('manys')->get(),
]);
}
}
{{-- iterate each one --}}
@foreach ($ones as $one)
{{-- iterate the manys of the one --}}
@foreach ($one->manys as $many)
...
@endforeach
@endforeach
我有一个具有一对多关系的模型,我想查看按关系分组的模型的所有记录。
比如我想输出这样的东西:
一个[1]
- 很多[1]
- 很多[2]
- 很多[3]
一个[2]
- 很多[4]
- 很多[5]
- 很多[6]
到目前为止,使用下面给出的代码我可以得到:
一个[1]
- 很多[1]
- 很多[2]
- 很多[3]
一个[2]
- 很多[1]
- 很多[2]
- 很多[3]
型号
class Many extends Model
{
public function ones()
{
return $this->hasOne('App\Models\One');
}
}
class One extends Model
{
public function manys()
{
return $this->hasMany('App\Models\Many');
}
}
控制器
class YeargroupController extends Controller
{
public function index()
{
$one = One::get();
$ones = One::find(1)->manys;
}}
观看次数
</div>@foreach ($ones as $row)
<div class="card-body">{{$row->name}}
<div class="row">@foreach ($one as $row)
{{$row->name}}
</div>@endforeach
</div>
</div> @endforeach
如何访问下一条记录的关系?
class YeargroupController extends Controller
{
public function index()
{
return view(..., [
// get all the 'ones' with their relationship loaded
'ones' => One::with('manys')->get(),
]);
}
}
{{-- iterate each one --}}
@foreach ($ones as $one)
{{-- iterate the manys of the one --}}
@foreach ($one->manys as $many)
...
@endforeach
@endforeach