抱歉新手问题。
我想每 1 小时更新相关表中的 1 列。例如:
表汽车
女巫hasMany
评论
在汽车
表中我有列:
id
日期时间
名称
公司
因此汽车表已经每 1 小时自动从外部 SQL 文件更新一次。
比我有comments
表女巫属于汽车
表。 comments
表包含以下列:
id
car_id
日期时间
名称
公司
正文
所以我想做的是每小时制作 comments
表复制 cars
中 datetime
列的数据。
基本上我想将两列同步到不同的表中。
有什么想法我可以实现吗?
最佳答案
我设法找到解决方案:https://laravel.com/docs/5.4/scheduling
所以我到底做了的是:
- 创建了一个函数来手动更新一行。
- 将此函数放入每个行的循环中。
- 然后添加一个调度程序以每 1 小时执行一次此函数。
- 在我的服务器上设置一个 crontab。
这是我的代码:
应用程序\控制台\Krenel.php
<?php
namespace App\Console;
use App\Comment;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
// \App\Console\Commands\Inspire::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$comments = Comment::all();
foreach ($comments as $comment)
{
if (empty($comment->cars->datetime)) {
//If the row do not exist, Do nothing
} else {
$comment->datetime = $comment->cars->datetime;
$comment->save();
}
}
})->hourly();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
关于php - 自动同步 Laravel 中的相关表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615358/