In my database i have table name post and have column name day i want to create a yii2 advanced console command that delete posts older than 3 days can any one help me ?
What you want to do is, create a Cron Job to delete the post older than 3 days
Step 1: Create a controller inside your console/controllers directory as shown below
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
use yii\helpers\Console;
class CronController extends Controller {
public function actionTest() {
echo "Test cron job"; // your logic for deleting old post goes here
exit();
}
}
Note: CronController
is the name of controller and action is test
Step 2: To run your cron job named test
you need to have yii
file inside your root directory. yii files code is shown below
#!/usr/bin/env php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/common/config/main.php'),
require(__DIR__ . '/common/config/main-local.php'),
require(__DIR__ . '/console/config/main.php'),
require(__DIR__ . '/console/config/main-local.php')
);
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
Note: Make sure that you have all the necessary config files present inside your console/config
directory.
Step 3: Now its time to run your cron job
Go to your root directory in command prompt/terminal and execute following command, and you must see the message echoed inside the test action.
php yii cron/test
Here
cron => name of the controller
test => name of the action