我的应用程序有 1000 万条记录。
公司表:
+---+------+-----------+-------------+------------+
|id | name |country_id | industry_id | finance_id |
+---+------+-----------+-------------+------------+
| 1 |LOrel | 1 | 1 | 1 |
+---+------+-----------+-------------+------------+
国家/地区表:
+---+-----------+
|id | name |
+---+-----------+
| 1 | USA |
+---+-----------+
| 2 | Romania |
+---+-----------+
行业表:
+---+-----------+
|id | name |
+---+-----------+
| 1 | Pharmacy |
+---+-----------+
| 2 | Software |
+---+-----------+
财务表:
+---+------------+------+--------+---------+------------+
|id | company_id | year |revenue | profit | loss |
+---+------------+------+--------+---------+------------+
| 1 | 1 | 2017 | 4,125 | 2045 | 750 |
+---+------------+------+--------+---------+------------+
| 2 | 1 | 2018 | 10,125 | 7045 | 125 |
+---+------------+------+--------+---------+------------+
| 3 | 2 | 2017 | 8,125 | 4045 | 750 |
+---+------------+------+--------+---------+------------+
| 4 | 3 | 2018 | 7,125 | 2045 | 125 |
+---+------------+------+--------+---------+------------+
这是我的数据库结构。
预期输出:
+---------+---------+----------+-----+--------+---------+
| Country | company | industry |year |revenue | profit |
+---------+---------+----------+-----+--------+---------+
| USA | LOrel | Pharmacy |2018 | 10,125 | 7045 |
+---------+---------+----------+-----+--------+---------+
我得到了我想要的相同结果,我正在使用 laravel 急切加载和 yajra laravel 数据表。
现在,我需要通过范围 slider 过滤数据,从数据库检索数据需要很长时间。
$company_data = Company::whereBetween('revenue',$request->slider)
->with('country','industry','company_financial')
->skip($request->start)->take($request->length)->get();
提前致谢
最佳答案
如果您只需要很少运行此查询(即每周一次),则将该任务卸载到 queue 。我建议使用 redis 作为驱动程序。
// WeeklyQueryJob.php
protected $slider;
protected $start;
protected $length;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($slider, $start, $length)
{
$this->slider = $slider;
$this->start = $start;
$this->length = $length;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$company_data = Company::whereBetween('revenue',$this->slider)
->with('country','industry','company_financial')
->skip($this->start)
->take($this->length)
->get();
// add logic to store/email/whatever the results
}
下一步设置scheduled task to queue the job
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->job(new WeeklyQueryJob)->weekly();
}
接下来,添加 entry to cron to run the scheduler
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
最后,使用supervisor start the queue worker and keep it running
关于php - 使用 Laravel Eloquent 关系从不同表快速检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48681486/