Dmitry Malys
Dmitry Malys

Reputation: 1323

Automatically sync related tables in Laravel

sorry for newbie question.

I want to update 1 column in related table every 1hour. For example:

Table cars witch hasMany comments

In cars table i have columns:

id datetime name company

So the car table is already updating automatically from external SQL file every 1 hour.

Than i have comments table witch belongsTo cars table. The comments table has columns:

id car_id datetime name company body

So what i want to do is make comments table every hour copy data for datetime column in cars.

Basically i want to Synchronise two columns in to different tables.

Any ideas who i can achieve that?

Upvotes: 0

Views: 1584

Answers (1)

Dmitry Malys
Dmitry Malys

Reputation: 1323

I manage to find a solution: https://laravel.com/docs/5.4/scheduling

So what exactly i did is:

  1. Created a function to manual update one row at the time.
  2. Put this function in to a loop foreach row.
  3. Than add a scheduler to preform this function every 1 hour.
  4. Set up a crontab on my server.

So this is my code:

App\Console\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');
    }
}

Upvotes: 1

Related Questions