首页 > 解决方案 > 运行 Laravel 任务计划命令时调用未定义的方法 Illuminate\Database\Eloquent\Builder::save()

问题描述

我正在尝试安排在何时运行的广告系列

subendsat 大于或等于当前时间

subendsat是用户表中的一列

在我的命令中,我有这个

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\User;
use Carbon\Carbon;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This Changes Role When The Subscription Expires';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $user = User::where('subendsat', '>=', Carbon::now())->get();
        $user->role = 'subscriber';
        $user->save();

    }
}

在我的内核中,我有这个

protected $commands = [
    //
    'App\Console\Commands\ChangeRole',
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
     $schedule->command('command:update')
              ->daily();
}

我在 Windows 中创建了一个这样的基本任务我有这个 .bat 文件

c:\xampp\php\php.exe 工匠计划:运行 1>> NUL 2>&1

  1. 转到 Windows 任务计划程序
  2. 单击创建基本任务,选择登录时触发器,然后选择启动程序 -> 您的 .bat 文件。
  3. 检查打开属性对话框选项,然后单击完成。
  4. 在任务属性中单击触发器,然后单击新建并添加新触发器每 1 分钟重复一次任务。

但是当我运行命令时

php artisan 命令:更新,它返回错误

调用未定义的方法 Illuminate\Database\Eloquent\Builder::save()

但这不会在运行时更新我的​​数据库。我不知道我在做什么。有人可以建议吗?谢谢。

标签: laravel

解决方案


您发布的代码不会引发该错误...您没有Builder该类的实例,因为->get()返回一个Collection. 但无论如何,修改 a Collection, via的属性$user->role = 'subscriber';是无效的......您需要循环$users正确命名变量)并更新每个$user

$users = User::where('subendsat', '>=', Carbon::now())->get();
foreach ($users as $user) {
  $user->role = 'subscriber';
  $user->save();
}

或调用批处理update()

User::where('subendsat', '>=', Carbon::now())->update([
  'role' => 'subscriber'
]);

推荐阅读