X
X
XenK2017-07-31 12:01:00
Yii
XenK, 2017-07-31 12:01:00

Yii2 get GriwView records?

There is such a database structure: It is necessary to display all authors for one book in a separate GridView
bc37d730954141929b72b8cf743a4fc1.PNG
column . I tried in the Authors model, to make such a connection:

/**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthorsBooks()
    {
        return $this->hasMany(AuthorsBooks::className(), ['authors_id' => 'id'])->viaTable('books', ['id' => 'books_id']);
    }

What is the best way to implement this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-07-31
@XenK

....
[
  'attribute'=>'authorsBooks',
  'value'=>function($model){
      return implode(',',ArrayMap::getColumn($model->authorsBooks,'name'));
    }
]
...

It is possible to implement a method in the model
public function getAutorsString(){
  return implode(',',ArrayMap::getColumn($this->authorsBooks,'name'));
}

respectively in gridView:
....
[
  'attribute'=>'authorsBooks',
  'value'=>'autorsString'
]
...

The second option is more logical as it avoids code duplication. As I understand it, there are many places where it is necessary to display.

B
Boris Korobkov, 2017-07-31
@BorisKorobkov

GridView::widget([
  ...
  'columns' => [
    ...
    'author' => [
      'label' => 'Авторы', 
      'format' => 'html',
      'value' => function (Book $book) {
        foreach($book->authorsBooks...
        return ...;
      },
    ],
  ],
])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question