是否有一种既定的方法来存储您可能想要在内存/缓存中处理的模型,而不是访问数据库?
我有带有 created_by
和 updated_by
列的模型,它们存储为User
id 的整数。我通常还会在前端显示创建每个模型的人的姓名。
假设登录用户与 created_by
列具有相同的 id
。我将始终检查登录用户的身份验证,但我不需要查询数据库两次,以便在发回 json 响应时也显示创建的用户名...
我有太多重复查询获取相同的确切用户,这会减慢应用程序的速度。
对于 UserRepository
中的方法来说,这是一个很好的用例吗?我还没有使用存储库,但想知道是否有其他人遇到过这个问题并提出了一个好的解决方案。
以下是可以查询多个用户的位置的示例:
// CompanyController.php
public function update(Request $request, Company $company)
{
// got user with ID = 1 here
$user = Auth::user();
if(!$user->can('update', $company)){
return response(403); //deny user
}
$company->fill($request->all());
$company->save();
// got user with ID = 1 here again...
// this model was created by the logged in user
return response()->json($company->with('created_user'));
}
// App\Company.php
public function created_user()
{
// get the user identified by ID in the created_by column
return $this->belongsTo(App\User::class, 'created_by');
}
我使用的是 Laravel 5.4 和 PHP 7.2
最佳答案
我遇到了同样的问题,并且没有太多时间为每个模型编写自己的存储库,我发现 https://github.com/AuthentikCanada/eloquent-cache/包非常容易使用。您只需向模型添加一个特征,它就会开始缓存您的查询。
关于mysql - Laravel:从数据库检索后将用户存储在存储库中以减少 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54754115/