简体   繁体   English

Yii2:如何显示两个相关表中的数据?

[英]Yii2: how to show data from two related tables?

I have the table persons(id_person, name_person, id_color) and the table colors(id_color, name_color) . 我有表人员(id_person,name_person,id_color)和表颜色(id_color,name_color)

I need to show names of the persons and the color name of every person inside a Select2 component. 我需要在Select2组件中显示人员名称和每个人的颜色名称。

I am using a Select2 component very similar to kartik-v/yii2-widget-select2 and 2amigos/yii2-select2-widget . 我正在使用与kartik-v / yii2-widget-select22 amigos /yii2-select2-widget非常相似的Select2组件。

I can do it creating an array with a SQL query but I would like to know if Yii2 provides a better and easy solution. 我可以用SQL查询创建一个数组,但是我想知道Yii2是否提供了更好,更简单的解决方案。

This solution works but I don't think it is the best: 此解决方案有效,但我认为这不是最佳解决方案:

public function personsList()
{
    $persons = \app\models\Persons::find()->orderBy('name_person')->all();
    $personsList = yii\helpers\ArrayHelper::map($persons, 'id_person', function($persons) {
        $color = \app\models\Colors::findOne(['id_color' => $persons->id_color]);
        $name_color = $color->name_color;
        return $persons->name_person . ' - ' . $name_color;
    });

    return $personsList;
}

I hope someone can improve it. 我希望有人可以改善它。

If you have defined the relations between the models a much cleaner and optimized way could be like below. 如果您定义了模型之间的关系,则更简洁,更优化的方法可能如下所示。

I assume you a relation with th name getColor() inside your Persons model. 我假设您在Persons模型中具有名称getColor()的关系。 Change your function personsList() to the following. 将函数personsList()更改为以下内容。

public function personsList() {
     $persons = rsons::find()->with('color')->orderBy('name_person')->all();
     return ArrayHelper::map($persons, 'id_person', function($persons) {
          return $persons->name_person . ' - ' . $persons->color->name_color;
     });
}

The above will return you an array like below 上面将返回如下数组

{
    "1": "omer aslam - red",
    "2": "irfan ashraf - blue",
    "3": "shaban khan - pink",
    "4": "rana touqeer - red",
    "5": "sajjad - blue"
}

EDIT 编辑

If you are saving multiple colors against the person which does not look the case as you have no junction table and the color is saved against the person in the persons table, but anyhow if it is one-to-many then change the callback function inside the ArrayHelper::map() to below so that it shows you all the colors associated to the person. 如果要为没有外观的情况下的人保存多种颜色,因为您没有联结表,并且针对person的颜色保存在persons表中,但是无论如何,如果颜色是one-to-many则在one-to-many更改回调函数ArrayHelper::map()移至下面,以便向您显示与该人关联的所有颜色。

function($persons) {
    return $persons->name_person . '-' . implode(",",\yii\helpers\ArrayHelper::getColumn($persons->color, 'name_color'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM