【发布时间】:2017-11-02 06:11:55
【问题描述】:
对 HomeController 文件的查询会降低网站速度。页面完全加载需要 20 秒。 (页面大小仅为 3.9 Mb,每次加载页面时 CPU 负载都会上升 80%)。我被告知使用比 Elequant 更快的查询生成器并加入查询以将它们作为一个查询发送。我觉得这太难了。我在哪里可以看到一些例子?
家庭控制器
public function index()
{
$sliders = Post::where('post_type','slider')
->with('FeaturedImage','PostField')
->orderBy('created_at', 'desc')
->limit(4)
->get();
$page1 = Post::where([
['post_type','=','custom_page'],
['slug','=','page1'],
])
->with('FeaturedImage','PostField')
->latest()
->first();
$page2 = Post::where([
['post_type','=','custom_page'],
['slug','=','page2'],
])
->with('FeaturedImage','PostField')
->latest()
->first();
$page3 = Post::where([
['post_type','=','custom_page'],
['slug','=','page-3'],
])
->with('FeaturedImage','PostField')
->latest()
->first();
$compacts = array(
'sliders',
'page1',
'page2',
'page3',
);
return view('site.home')->with(compact($compacts));
}
编辑: 迁移后
public function up()
{
// Create table for storing roles
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('author_id');
$table->integer('category_id')->nullable();
$table->string('title');
$table->text('excerpt')->nullable();
$table->text('body')->nullable();
$table->string('slug')->nullable();//unique()
$table->string('post_type')->default('post');
$table->enum('status', ['PUBLISHED', 'DRAFT', 'PENDING'])->default('DRAFT');
$table->timestamps();
});
}
【问题讨论】:
-
我在哪里可以看到一些例子?你试过谷歌吗? laravel 文档?
-
你基本上是无缘无故地执行了 3 次查询
-
如何将此查询合并为一个查询?
-
你能展示你的帖子表的迁移吗?
-
@patricus 是的,我更新了
标签: php mysql laravel query-optimization laravel-5.3