Php Variable in Cakephp Model

老子叫甜甜 提交于 2019-12-13 02:46:39

问题


I am trying to use join with two table by using has many relation of CakePHP with condition my model code are here which am using

public $userid = 3;
    public $name = 'Course';
    public $hasMany = array(
        'Enrollcourse' => array(
            'className'     => 'Enrollcourse',
            'foreignKey'    => 'course_id',
            'conditions'    => array('Enrollcourse.student_id' => $this->userid),
            'dependent'     => true
        )
    );

OR

   public $userid = 3;
        public $name = 'Course';
        public $hasMany = array(
            'Enrollcourse' => array(
                'className'     => 'Enrollcourse',
                'foreignKey'    => 'course_id',
                'conditions'    => array('Enrollcourse.student_id' => $userid),
                'dependent'     => true
            )
        );

here is $userid is a variable which is used to check to retrieve data of selected user but am unable to get this & following are occur

Error: parse error
File: E:\wamp\www\simpleApp\app\Model\course.php
Line: 10

Any help?


回答1:


You cannot use variables in the declaration of a variable within a class. This means that use of $userid will cause the parse error you are seeing.

The best way to overcome this for dynamic information is to replace/overload the constructor for the model:

public function __construct($id = false, $table = null, $ds = null) {
    $this->hasMany = array(
        'Enrollcourse' => array(
            'className'     => 'Enrollcourse',
            'foreignKey'    => 'course_id',
            'conditions'    => array('Enrollcourse.student_id' => $this->userid),
            'dependent'     => true
        )
    );
    parent::__construct($id, $table, $ds);
}

This overcomes the use of a variable during a class variable declaration.



来源:https://stackoverflow.com/questions/11840406/php-variable-in-cakephp-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!