GridView from many to many relationship. Column showing (not set)

Hello, this is my first post. I looked all over the internet but could not find a solution to this issue. The weird part is I have other grids from a many to many relationship that work just fine but this one is giving me a problem.

I have a many to many relationship between users and courses. One user can be join many courses and one course can have many users.

Here is my User model relationship…




    /**

     * @return \yii\db\ActiveQuery

     */

    public function getCourses()

    {

        return $this->hasMany(Course::className(), ['id' => 'course_id'])->viaTable('course_user', ['user_id' => 'id']);

    }



here is my Course model relationship




   /** 

    * @return \yii\db\ActiveQuery 

    */ 

   public function getUsers()

   { 

       return $this->hasMany(User::className(), ['id' => 'user_id'])->viaTable('course_user', ['course_id' => 'id']); 

   } 



this is my controller action that create the dataprovider for the form…




    public function actionUpdate($id)

    {

        //get course

        $model = $this->findCourseModel($id);

        

        //get users active query for dataprovider

        $query = $model->getUsers();

        

        //create dataprovider for gridview

        $dataProvider = new ActiveDataProvider([

            'query' => $query,

        ]);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } 

        else {

            return $this->render('update', [

                'model' => $model,

                'dataProvider' => $dataProvider,

            ]);

        }

    }



and here is my gridview. The column that is having the problem is the ‘courses.name’ one…


    

<?= GridView::widget([

        'dataProvider' => $dataProvider,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],

            'courses.name',

            'username',

            'first_name',

            'last_name',

            'gender',

            'status',



When I do a print_r on $query object I can see that I do have the Course name so the sql query gyazo.com/249aab9291cc23df85eca8721c20a170, but it shows up as "(not set)" on the gridview, gyazo.com/abe72ce4e2f6fbca330991d7dc0df1a2.

I have successfully done this same thing woth other many to many relationships but I can;t figure out why this doesn;t work. Can anyone point me in the right direction?

Thanks.

Ok, I figured out the problem. Please ignore this thread. However, if anyone wants to know I should have been using.


$query = $model->getCourseUsers();

instead of


$query = $model->getUsers();

the CourseUsers model should have the following relationships…




    /**

     * @return \yii\db\ActiveQuery

     */

    public function getCourse()

    {

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

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getUser()

    {

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

    }



and the gridview should look like this…


    

<?= GridView::widget([

        'dataProvider' => $dataProvider,

        //'filterModel' => $searchModel,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],

            'course.name',

            'user.username',

            'user.first_name',

            'user.last_name',

            'user.gender',

            'user.status',


        ],

    ]); ?>



i m facing the same many to many problem in gridview, i have 3 tables groups,contacts and contactsgroups following is my code

in contact model





    public function getContactsgroups() {

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

    }


    public function getGroups() {

        return $this->hasMany(Groups::className(), ['id' => 'group_id'])->viaTable('tblcontactsgroups', ['contact_id' => 'id']);

    }



in groups model





    public function getContacsgroups() {

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

    }


    public function getContacts() {

        return $this->hasMany(Contacts::className(), ['id' => 'contact_id'])->viaTable('tblcontactsgroups', ['group_id' => 'id']);

    }




and in contactsgroups(the junction table)




  public function getContacts()

    {

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

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getGroups()

    {

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

    }



and following is my contactscontroller




   public function actionIndex()

    {

       $model = new Contacts();

       // print_r( Yii::$app->request->queryParams);

       // exit;

       // $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $query = $model->getContactsgroups();

        $dataProvider = new ActiveDataProvider([

            'query' => $query

        ]);


        return $this->render('index', [

         //   'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }



following is the code for my gridview




 GridView::widget([

        'dataProvider' => $dataProvider,

     //   'filterModel' => $searchModel,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],

            //  'id',

            [

                'label' => 'First Name',

                'attribute' => 'contacts.firstname',

            ],

            [

                'label' => 'Last Name',

                'attribute' => 'contacts.lastname',

            ],

            //  'company',

            // 'address:ntext',

            // 'phone',

            //// 'mobile',

            // 'fax',

             'groups.groupname',

            [

                'label' => 'Primary Email',

                'attribute' => 'contacts.pemail',

            ],

            // 'semail:email',

            // 'country',

            // 'websiteurl:url',

            // 'gender',

            // 'birthday',

            // 'status',

            // 'sentstatus',

            // 'addeddate',

            // 'updateddate',

            ['class' => 'yii\grid\ActionColumn'],

        ],

    ]);



i got nothing in the gridview please help me

You could use the original CRUD code that Gii had generated for you.

All you have to do is display the ‘has many’ attributes in grid view.




 GridView::widget([

        'dataProvider' => $dataProvider,

        'columns' => [

            ['class' => 'yii\grid\SerialColumn'],

            [

                'label' => 'First Name',

                'attribute' => 'firstname',

            ],

            [

                'label' => 'Last Name',

                'attribute' => 'lastname',

            ],

            [

                'label' => 'Groups',

                'format' => 'ntext',

                'value' => function($model) {

                    foreach($model->groups as $group) {

                       $groupNames[] = $group->name;

                    }

                    return implode("\n", groupNames);

                },

            },

            [

                'label' => 'Primary Email',

                'attribute' => 'pemail',

            ],

            ['class' => 'yii\grid\ActionColumn'],

        ],

    ]);



Since a contact can have many groups, you have to loop through all the groups of a contact.

And additionally you can optimize the "search" method of ContactsSearch model using "with".




    $query = Contacts::find()->with('groups');



you are right,thank you very much for solving my problem, thanks