我有一个我正在使用的Laravel用户存储库,但为了防止总是唠叨的N + 1问题,我试图让我的所有用户返回他们在用户数组中的角色和状态。
正如您现在所看到的,它的运行方式是我的运行方式,因为我的数据库中的任何记录都是我的运行次数,因此我的运行次数是我的 200+ 倍。所以我正试图减少它。
我将如何做到这一点?
<?php namespace Backstage'Repositories'Users;
use User;
use Backstage'Repositories'DbRepository;
class DbUserRepository extends DbRepository implements UserRepositoryInterface {
protected $model;
function __construct(User $model)
{
$this->model = $model;
}
}
views/users/parts/table.blade.php
<td>{{ $user->id }}</td>
<td>{{ $user->full_name }}</td>
<td>{{ $user->email_address }}</td>
<td>{{ $user->role->name }}</td>
<td>{{ $user->status->name }}</td>
你可以使用急切加载来摆脱 N+1 问题,请参阅文档
您没有包括您的模型,因此不能 100% 确定命名,但我认为您需要这个:
function __construct(User $model)
{
$this->model = $model;
$this->model->load('roles');
}
但是,这总是急于加载 DbUserRepository 的角色。您也可以仅以正确的方法调用 ->load('roles')。