A
A
Alexey2016-05-25 18:37:56
MySQL
Alexey, 2016-05-25 18:37:56

How to output a query with INNER JOIN in Yii2?

Comrades, I can not understand how to display data from two tables with inner join on the page.
Even more precisely, I can’t implement the output of my own request at all. I read a lot of documentation and questions, but I still don’t understand.
There are two tables: teachers and discipline. discipline has a teacher_id column. It is necessary to display teachers from teachers with the names of disciplines attached to them from discipline (teachers.id = discipline.teacher_id).
The request itself works as it should.

SELECT
`teachers`.`FIO`,
`discipline`.`name`
FROM
`teachers` INNER JOIN `discipline`
ON
`teachers`.`id` = `discipline`.teacher_id

How to make a request so that you can bring disciplines to the teacher? According to the documentation, it is not possible to create your own request so that it works in the views file.
The output to the page is now like this.
Controller (for page views/teachers/all.php)
...
    public function actionAll()
    {
        $query = Teachers::find();
        
        $pagination = new Pagination([
            'defaultPageSize' => 15,
            'totalCount' => $query->count(),
        ]);

        $teachers = $query->orderBy('FIO')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('all', [
            'teachers' => $teachers,
            'pagination' => $pagination,
        ]);
    }
...

Model
class Teachers extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'teachers';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'FIO'], 'required'],
            [['id', 'lead_krb', 'lead_magist', 'ped_practices', 'jobs_zav_kaf', 'lead_aspir'], 'integer'],
            [['classes_subject', 'lead_practice', 'job_gak'], 'number'],
            [['FIO'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'FIO' => 'ФИО',
            'classes_subject' => 'Занятия по дисциплинам',
            'lead_practice' => 'Рук-во практикой',
            'lead_krb' => 'Рук-во КРБ',
            'lead_magist' => 'Рук-во маг.диссертацией',
            'ped_practices' => 'Пед. практика',
            'job_gak' => 'Работа ГАК, защита',
            'jobs_zav_kaf' => 'Работа по заданию зав.каф.',
            'lead_aspir' => 'Рук-во аспирантами',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDisciplines()
    {
        return $this->hasMany(Discipline::className(), ['teacher_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return TeachersQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new TeachersQuery(get_called_class());
    }

Performance
<h1>Преподаватели</h1>
<table class="table table-hover table-bordered">
    <thead>
    <tr>
        <th>ФИО</th>
        <th>Дисциплина</th>
        <th>Занятия по дисциплинам</th>
        <th>Руководство практикой</th>
        <th>Руководства КРБ</th>
        <th>Руководство маг.диссертацией</th>
        <th>Педагогич. практика</th>
        <th>Работа ГАК, защита</th>
        <th>Работа по заданию зав.каф.</th>
        <th>Руководство аспирантами</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($teachers as $teacher): ?>
    <tr>
        <td><?= $teacher->FIO ?></td>
        <td> дисциплина</td>
        <td><?= $teacher->classes_subject ?></td>
        <td><?= $teacher->lead_practice ?></td>
        <td><?= $teacher->lead_krb ?></td>
        <td><?= $teacher->lead_magist ?></td>
        <td><?= $teacher->ped_practices ?></td>
        <td><?= $teacher->job_gak ?></td>
        <td><?= $teacher->jobs_zav_kaf ?></td>
        <td><?= $teacher->lead_aspir ?></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?= LinkPager::widget(['pagination' => $pagination]) ?>

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
V
Vit, 2016-05-25
@Deia

$teachers = Teachers::find()->with('disciplines')->all();

    <?php foreach ($teachers as $teacher): ?>
    <tr>
        <td><?= $teacher->FIO ?></td>
        <td>
             <ul>
                  <?php foreach ($teacher->disciplines as $d): ?>
                          <li><?php echo $d->name; ?></li>
                  <? endforeach;?>
            </ul>
        </td>
        <td><?= $teacher->classes_subject ?></td>
        <td><?= $teacher->lead_practice ?></td>
        <td><?= $teacher->lead_krb ?></td>
        <td><?= $teacher->lead_magist ?></td>
        <td><?= $teacher->ped_practices ?></td>
        <td><?= $teacher->job_gak ?></td>
        <td><?= $teacher->jobs_zav_kaf ?></td>
        <td><?= $teacher->lead_aspir ?></td>
    </tr>
    <?php endforeach; ?>

More or less like this. Under the hood, however, inner join will not be done, but why do you need it? If you write with(relationName) it will work fine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question