Php 如何在Yii2中显示表中的数据以及查询另一个表中的每行数据

Php 如何在Yii2中显示表中的数据以及查询另一个表中的每行数据,php,mysql,yii,Php,Mysql,Yii,我有两张桌子——动物型和动物型 动物类型中的列:id和type 动物中的列:id、name和动物类型 我想在同一页上呈现动物类型和存在的动物列表 对于渲染动物类型,我创建模型动物\u类型,控制器动物\u类型控制器 <?php namespace frontend\controllers; use yii\web\Controller; use yii\data\Pagination; use app\models\Animals_type; class Animals_typeCont

我有两张桌子——动物型和动物型

动物类型中的列:idtype

动物中的列:idname动物类型

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

对于渲染动物类型,我创建模型动物\u类型,控制器动物\u类型控制器

<?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,
        ]);
    }
}

动物类型
  • :

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

在创建动物关系后,您可以这样使用它:

<?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 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; ?>