简体   繁体   中英

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) .

I need to show names of the persons and the color name of every person inside a Select2 component.

I am using a Select2 component very similar to kartik-v/yii2-widget-select2 and 2amigos/yii2-select2-widget .

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.

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. Change your function personsList() to the following.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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