E
E
Eugene2018-02-20 15:21:55
Yii
Eugene, 2018-02-20 15:21:55

How to get an object with related data?

There are two tables. Categories and doctors. In order not to suffer a one-to-many relationship.

Category Model
use yii\db\ActiveRecord;

class Category extends ActiveRecord
{
    public static function tableName()
    {
        return 'category';

    }
    public function getDoc()
    {
        return $this->hasMany(Doctor::className(), ['category_id'=> 'id']);
    }


}
Model Doctor
use yii\db\ActiveRecord;

class Doctor extends ActiveRecord
{
    public static function tableName()
    {
        return 'doctors';
    }
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id'=> 'category_id']);
    }

}

There are two models. What is the point.
Widget created. And in the widget in the run () method I want to get an object converted into an array where in each category, doctors are dragged in as a child or something similar
. An array of categories is easy to get
public function run()
    {
        $this->data=Category::find()->indexBy('id')->asArray()->all();
        debug($this->data2);
        return $this->tpl;

    }

But how to get exactly a more complex array with categories and doctors?
Further, it makes sense to form a list of categories and a nested list of doctors in each category through foreach.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2018-02-20
@evgen9586

$this->data=Category::find()->with(['doc'])->indexBy('id')->asArray()->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question