S
S
Sergey Beloventsev2017-08-25 09:33:29
Yii
Sergey Beloventsev, 2017-08-25 09:33:29

How to get id array of related hasMany models?

Here are the models in brackets attributes Category (id, title), CatToProd (id, id_category, id_product), Product (id, title)
here are the links in the Product model

public function getCategorys(){
        return $this->hasMany(Category::className(),['id'=>'id_category'])->viaTable('cat_to_prod', ['id_product' => 'id']);
    }

    public function getCatToProd(){
        return $this->hasMany(CatToProd::className(),['id_product' => 'id']);
    }

this is how i try to get category id to use in select2
public function getDataCategory($model){
        $categorys=$model->categorys;
        $arrResult=array();
        foreach ($categorys as $category){
            $arrResult[]=$category->id;
        }
        return $arrResult;
    }

I don't really like this code but how do you get. Get an array like [1,2,3]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
davidnum95, 2017-08-25
@Sergalas

public function getDataCategory($model){
       return array_column($model->categorys, 'id');
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question