1

I have being struggling with related model data for a while and can't seem to pin point the problem, I have been reduced to using a very simple example.

I have two models Dog and Owner, which have the following relations.

Owner:

public function getDogs()
{
    return $this->hasMany(Dog::className(), ['owner_id' => 'id']);
}

Dog:

public function getOwner()
{
    return $this->hasOne(Owner::className(), ['id' => 'owner_id']);
}

As a simple test I want to get the dog to disaply from the grid view in the index page in Owner view This is my index.php in the Owner view

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'name',
        [       
            'attribute' => 'type',
            'value' => 'dog.type',
        ],

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

I must be missing something fundamental here?

7
  • What's the current problem / error? Commented Apr 30, 2015 at 10:47
  • Current error is Getting unknown property: app\models\Owner::dog Commented Apr 30, 2015 at 11:43
  • 1
    Check relations, there are some mistakes there. They reference to the same type of object. And If the owner has many dogs, you can't access relation as dog, since it's dogs. Commented Apr 30, 2015 at 11:56
  • I am looking at the relations, but I can't seem to find any problems. they were generated directly from Gii. What problems do you see? I did however change the dog to dogs and now the page loads, but not the value, it just says in the Type column not set Commented Apr 30, 2015 at 12:16
  • do you use ->with('dogs') in your query? Commented Apr 30, 2015 at 12:41

1 Answer 1

7

You cannot display multiple related items like this, but you could simply use a callback, e.g. :

[
    'label' => 'Dog types',
    'value' => function($model) {
        return join(', ', yii\helpers\ArrayHelper::map($model->dogs, 'id', 'type'));
    },
],
Sign up to request clarification or add additional context in comments.

2 Comments

The yii2 version of GROUP_CONCAT. Lovely solution.
Thanks that's just what I needed. Now so you say I would not be able to display multiple related items like this but what about doing it the other way, from the Dog view, can I display the Owner information using my method above? As Any particular dog can only have one owner at a time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.