user7282
user7282

Reputation: 5196

Yii2 Join multiple tables

I have a table

CREATE TABLE IF NOT EXISTS `register` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `student_id` varchar(15) NOT NULL,
  `title` varchar(100) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(50) NOT NULL,
  `gsm` varchar(15) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `birth_date` date NOT NULL,
  `department_id` int(2) NOT NULL,
  `specialization` varchar(150) NOT NULL,
  `level_id` int(2) NOT NULL,
  `reason` varchar(2000) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

which have relation with two tables department and level

CREATE TABLE IF NOT EXISTS `level` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

and

CREATE TABLE IF NOT EXISTS `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department` varchar(300) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

I have made relation in Register model as

public function getDepartments() {
        return $this->hasOne(app\models\Department::className(), ['id' => 'department_id']);
    }

But in view.php (view file )when I use

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'student_id',
            'name',
            'email:email',
            'gsm',
            'gender',
            'birth_date',

 'department' ,
            'specialization',
            'level',
            'reason',
        ],
    ]) ?> ,

the department is shown as 'not set'. Also print_r($model);?> shows [department] =>(i.e, blank) . What is the issue here ?

Upvotes: 0

Views: 1943

Answers (2)

anruence
anruence

Reputation: 1

better change getDepartments to getDepartment as this is a hasOne relation.

[
  'attribute' => 'department_id', 
  'value' => isset($model->department) ? $model->department->department : ''
]

Upvotes: 0

Insane Skull
Insane Skull

Reputation: 9358

Use $model->relationName->field_name:

[
'attribute' => 'department_id', 
'value' => $model->departments->department
],

And add department model in register model.

Upvotes: 2

Related Questions