Laravel计划任务无法访问模型的属性

时间:2019-02-15 14:53:04

标签: laravel cron

在我的Laravel任务计划程序中,我试图制作模型的对象并调用该模型的函数。在函数内部,我试图使用$ this关键字访问模型属性。它将引发异常,指示未定义属性。请注意,相同的代码在普通控制器中可以正常工作,并且只有当我由任务计划程序运行它时,才会发生异常。

这是我在kernel.php中的代码的简化版本

$schedule->call(function () {
   $group_set_id = 8345;       
   $group_set = new GroupCategory(['group_set_id' => $group_set_id]);
   $group_set->changeSelfSignup(true);                
}

这是我在模型中所拥有的:

class GroupCategory extends Model
{
protected $fillable = [
    'id', 'group_set_id', 'course_ids', 'course_names', 'section_ids', 'section_names', 'auto_update'
];

protected $attributes = [
    'id',
    'group_set_id' => '',
    'name' => '',
    'role' => '',
    'self_signup' => null,
    'auto_leader' => null,
    'context_type' => '',
    'account_id' => '',
    'group_limit' => null,
    'sis_group_category_id' => null,
    'sis_import_id' => null,
    'progress' => null
];

protected $primaryKey = 'id';

public $timestamps = true;

public function getGroupCategoryGroups()
{
    $type = 'get';
    $form_params = ['include' => 'email'];
    $url = APIUtility::getGroupCategoryGroupsURL($this->group_set_id) . '?per_page=100';
    return APIUtility::getResponse($type, $url, $form_params);
}

public function createGroup(string $group_name)
{
    $type = 'post';
    $form_params = ['name' => $group_name];
    $url = APIUtility::createGroupURL($this->group_set_id);
    return APIUtility::getResponse($type, $url, $form_params);
}

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
}

protected $primaryKey = 'id';

public function changeSelfSignup(bool $is_self_signup_allowed)
{
    $type = 'put';
    $form_params = ['self_signup' => $is_self_signup_allowed ? 'enabled' : 'disabled'];
    $url = APIUtility::getSelfSignupURL($this->group_set_id);
    return APIUtility::getResponse($type, $url, $form_params);
}

这是我得到的例外:

ErrorException: Undefined variable: group_set_id in /var/www/utagt/app/GroupCategory.php:78

任何想法都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

我对代码进行了更改,使其可以正常工作,但我仍然不知道为什么无法访问该属性。这是我更改代码的方式:

在GroupCategory模型中:

public function changeSelfSignup(bool $is_self_signup_allowed, $group_set_id = '')
{
    $group_set_id = $group_set_id === '' ? $this->$group_set_id : $group_set_id;
    $type = 'put';
    $form_params = ['self_signup' => $is_self_signup_allowed ? 'enabled' : 'disabled'];
    $url = APIUtility::getSelfSignupURL($group_set_id);
    return APIUtility::getResponse($type, $url, $form_params);
}

在我的任务计划程序中:

$schedule->call(function () {
   $group_set_id = 8345;       
   $group_set = new GroupCategory(['group_set_id' => $group_set_id]);
   $group_set->changeSelfSignup(true, $group_set_id);                
}