【问题标题】:Laravel commands do not save and update to databaseLaravel 命令不保存和更新到数据库
【发布时间】:2017-09-18 13:47:29
【问题描述】:

我正在编写一个游戏模拟器,并想创建一个 cron 作业来每天运行游戏。我正在使用 Laravel 的命令和调度程序来执行此操作。

任务很简单。我只想从数据库中提取一条记录并在每次命令运行时更新它。但是我注意到更改有时不会保存到数据库中。我在过去 4 天里尝试过调试,但它看起来很随机,我没有看到任何模式。我在更新前后打印了记录,它显示它更新得很好。但是当我检查我的数据库时,有时它没有显示任何变化。好像有时更改在更新后会随机恢复。但我没有收到任何错误消息。除了 TeamRecord 记录之外,我还尝试更新其他对象并遇到相同的随机还原问题。有什么我想念的吗?下面是我的 Laravel 命令的代码。我使用 php artisan games:run 来运行它。

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use App\Game;
use App\MainLine;
use App\GameLog;
use App\TeamRecord;

class RunGames extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'games:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Get the record from the database
        $record1 = $g->homeTeam()->teamRecords->sortByDesc('season_number')->first();
        // This shows the current data
        $this->info($record1);

        // Update the record to the database
        TeamRecord::where('id', $record1->id)->update(['games_played' => $record1->games_played + 1]);
        // This always shows the data has changed. But when I check the database, sometimes the record did not change.
        $this->info(TeamRecord::find($record1->id));
    }

【问题讨论】:

  • 你的句柄方法中的$g是什么?

标签: php mysql laravel


【解决方案1】:

cron 用户可能没有对storage/logs/laravel.log 以及它可能需要写入的任何其他内容的写入权限。

添加

\Log::error('This definitely should have run!');

handle() 的第一行,看看它是否有写权限。您也可以使用它来进一步调试它。

【讨论】:

    【解决方案2】:

    我看到您没有将$g 传递给函数(或构造)。命令不一定会引发错误。

    public function handle()
        {
            // Get the record from the database
            $record1 = $g->homeTeam()->teamRecords->sortByDesc('season_number')->first();
            // This shows the current data
            $this->info($record1);
    
            // Update the record to the database
            TeamRecord::where('id', $record1->id)->update(['games_played' => $record1->games_played + 1]);
            // This always shows the data has changed. But when I check the database, sometimes the record did not change.
            $this->info(TeamRecord::find($record1->id));
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多