php - Yii2如何显示表格中的数据并查询另一个表格中的每一行数据

标签 php mysql yii

我有两个表 - animals 和 animals_type。

animals_type 中的列:idtype

animals 中的列:idnameanimals_type

我想在同一页面上呈现动物类型和存在动物的列表。

为了渲染动物类型,我创建模型 Animals_type、 Controller Animals_TypeController

<?php
namespace frontend\controllers;

use yii\web\Controller;
use yii\data\Pagination;
use app\models\Animals_type;

class Animals_typeController extends Controller
{
    public function actionIndex()
    {
        $query = Animals_type::find();

        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount' => $query->count(),
        ]);

        $Animals_type = $query->orderBy('id')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('index', [
            'animals_type' => $Animals_type,
            'pagination' => $pagination,
        ]);
    }
}

并查看index.php

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;

?>
    <h1>Animals Type</h1>
    <ul>
        <?php foreach ($animals_types as $animals_type):?>
            <li>
                <?= Html::encode("{$animals_type->type} ({$animals_type->id})") ?>:
            </li>
        <?php endforeach; ?>
    </ul>

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

如何查询每种类型的动物列表?

最佳答案

在创建关系 animals 之后,你可以像这样使用它:

<?php foreach ($animals_types as $animals_type):?>
    <li>
        <?= Html::encode("{$animals_type->type} ({$animals_type->id})") ?>:
    <?if($animals_type->animals):?>
        <ul>
            <?php foreach ($animals_type->animals as $animal):?>
                <?= Html::encode("{$animal->name} ({$animal->id})") ?>:
            <?php endforeach; ?>
        </ul>
    <?endif?>
    </li>
<?php endforeach; ?>

关于php - Yii2如何显示表格中的数据并查询另一个表格中的每一行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29395863/

相关文章:

MySQL group_concat问题

MySQL:子查询未知列

php - 支持事务、行级锁定和外键 errorno 150

php - 如何返回我在同一查询中创建/或之前创建的记录

php - 如何修复意外的 T 变量错误

php - Javascript 意外标记换行中非法

php - 带有复杂 $textField 的 CHtml::listData

jquery - 避免在 Yii 中捆绑 jquery

php - 在 yii2 中显示多个相关数据

php - 没有大括号的 JavaScript if 语句的简洁语法