默认情况下将 Laravel Eloquent 模型设置为预先加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33787137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:43:06  来源:igfitidea点击:

Set Laravel Eloquent model's to eager load by default

phplaravel

提问by elixir

Laravel's eloquent models are set to lazy load by default. The problem is that it makes a lot of query to the database and especially during high traffic, the laravel application crashes whereas a similar application build on Yii 1 has no issues.

Laravel 的 eloquent 模型默认设置为延迟加载。问题是它对数据库进行了大量查询,尤其是在高流量期间,laravel 应用程序崩溃,而在 Yii 1 上构建的类似应用程序没有问题。

After installing the Laravel's debug bar, the problem is too many queries being made on every page load. The next step is to query optimization. I have been using eager loading as directed in the Laravel's documentation but still too many queries.

安装了 Laravel 的 debug bar 后,问题是每次加载页面都会进行过多的查询。下一步是查询优化。我一直在按照 Laravel 文档中的指示使用预先加载,但仍然有太多查询。

I was wondering if there is a way to set Eloquent to only "Eager Load" in dev environment. That way when the page fails to load, identifying issue would be easier.

我想知道是否有办法在开发环境中将 Eloquent 设置为“Eager Load”。这样当页面加载失败时,识别问题会更容易。

回答by Louis Carrese

You could set defaults relations to "eager load" directly on the models :

您可以直接在模型上将默认关系设置为“急切加载”:

Class MyModel extends Model {
  protected $with = ['relation'];
}

回答by vpedrosa

The solution for high database load is Cache.

高数据库负载的解决方案是Cache

Caching properly could give you incredible performance during high traffic, because it reduces common database queries to zero, and redirect them to RAM ones, which are faster.

正确缓存可以在高流量期间为您提供令人难以置信的性能,因为它将常见的数据库查询减少到零,并将它们重定向到更快的 RAM 查询。

Enabling Route Cachingwill increase perfomance too:

启用路由缓存也会提高性能:

php artisan route:cache

EDIT:

编辑:

As Fx32points, you should make sure that you need Eloquent and wouldn't be better to make the same query directly to the DB, joining the tables you need and making a single query instead of a lot:

作为Fx32点,你应该确保你需要 Eloquent 并且直接对数据库进行相同的查询,加入你需要的表并进行单个查询而不是很多:

Cache is not a good solution as a fix for bad database querying. Eloquent is great, but often it's better to write proper queries with some joins. Don't just bash away at your DB and then throw all the results in a cache, as it will introduce new problems. If your use case is not a flat CRUD API, ActiveRecord patterns might not be the best solution anyway. If you carefully select and join results from the DB, and want to speed up retrieval of such items, caching can help.

缓存不是修复错误数据库查询的好方法。Eloquent 很棒,但通常用一些连接编写正确的查询会更好。不要只是猛烈抨击您的数据库,然后将所有结果都放入缓存中,因为这会带来新问题。如果您的用例不是平面 CRUD API,则无论如何 ActiveRecord 模式可能都不是最佳解决方案。如果您仔细选择并连接来自数据库的结果,并希望加快检索此类项目的速度,缓存会有所帮助。