how to show multiple values in gridview with hanMany relation




class Book extends ActiveRecord

{

    ....


    public static function tableName()

    {

        return 'books';

    }


    public function getAuthor()

    {

        return $this->hasOne(Author::className(), ['id' => 'author_id']);

    }



And Author




class Author extends ActiveRecord

{


    public static function tableName()

    {

        return 'authors';

    }


    public function getBooks()

    {

        return $this->hasMany(Book::className(), ['author_id' => 'id']);

    }






i just want to get author name with books how to do that in girdview in Yii2. I want multiple comma separated books names in a single column just like following




Author               Books

Alex                  C++ Programming,Yii Book,Java Cookbook




What should i do? please help(In Yii 2.0 GridView)


$authorWithBooks = Author::find()->joinWith('books')->all();

[color="#006400"]/* moved from Tips, Tricks and Tutorials */[/color]

Something like this:




'columns' => [

    'name', // author's name

    [

        'label' => 'Books',

        'value' => function($data) {

            $bookTitles = [];

            foreach($data->books as $book) {

                $bookTitles[] = $book->title;

            }

            return implode(',', $bookTitles);

        },

    ],

]



Please take a look at the following section of the guide.

http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#gridview

And also the relevant part of the API reference.

@onmotion:

"joinWith" is not always necessary.

http://www.yiiframework.com/wiki/834/relational-query-lazy-loadnig-and-eager-loading-in-yii-2-0

1 Like