php - 自动同步 Laravel 中的相关表

标签 php mysql laravel-5.4

抱歉新手问题。

我想每 1 小时更新相关表中的 1 列。例如:

汽车女巫hasMany 评论

汽车表中我有列:

id 日期时间 名称 公司

因此汽车表已经每 1 小时自动从外部 SQL 文件更新一次。

比我有comments表女巫属于汽车表。 comments 表包含以下列:

id car_id 日期时间 名称 公司 正文

所以我想做的是每小时制作 comments 表复制 carsdatetime 列的数据。

基本上我想将两列同步到不同的表中。

有什么想法我可以实现吗?

最佳答案

我设法找到解决方案:https://laravel.com/docs/5.4/scheduling

所以我到底做了的是:

  1. 创建了一个函数来手动更新一行。
  2. 将此函数放入每个行的循环中。
  3. 然后添加一个调度程序以每 1 小时执行一次此函数。
  4. 在我的服务器上设置一个 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/

相关文章:

php - @font-face 或自定义字体在 PHP pdf 生成器类中不起作用

php - 当写入 73 个或更多元素时 MySQL 服务器已消失

php - 未定义值单个复选框javascript到另一个页面

php - 没有重复记录的内部连接

python - 我可以使用触发器来添加外键组合吗?

php - 使用 Laravel dusk 只迁移一次

php - 获取所有类别(多级)

MYSQL/Laravel 迁移将复合键更改为自动增量

node.js - Laravel 和 bootstrap glyphicons - 文件复制到哪里,如何设置相对路径以及如何解决 cachebusting?

php - 通过Phpmyadmin登录Mysql的问题