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

问题描述 投票:0回答:1

在我的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

任何想法将不胜感激。

laravel cron
1个回答
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);                
}    
© www.soinside.com 2019 - 2024. All rights reserved.