0
votes

This is my user model

class User extends \yii\db\ActiveRecord
{

public static function tableName()
{
    return 'user';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [[ 'created_at', 'updated_at', 'branch_id', 'postcode', 'tel_no', 'child_no','company_id'], 'integer'],
      //  [['branch_id', 'edu_level', 'date_joined','address1','country','state','city','postcode','race','position_level','religion','gender','staff_id','username','password','ic_number','tel_no','marital_status','child_no','bumi_status','resident_status','email','company_id'], 'required'],
        [['get_mail', 'gender', 'marital_status', 'resident_status', 'bumi_status','designation','status'], 'string'],
        [['date_joined'], 'safe'],
        [['staff_id', 'password', 'edu_level', 'position_level', 'address2', 'address3', 'address4', 'country', 'state', 'city', 'race', 'religion'], 'string', 'max' => 100],
        [['username', 'fullname', 'password_hash', 'password_reset_token', 'email', 'auth_key'], 'string', 'max' => 255],
        [['ic_number'], 'string', 'max' => 14],
        [['address1'], 'string', 'max' => 1000],
        [['staff_id'], 'unique'],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => Yii::t('user', 'ID'),
        'staff_id' => Yii::t('user', 'Staff ID'),
        'username' => Yii::t('user', 'Username'),
        'fullname' => Yii::t('user', 'Fullname'),
        'password' => Yii::t('user', 'Password'),
        'password_hash' => Yii::t('user', 'Password Hash'),
        'password_reset_token' => Yii::t('user', 'Password Reset Token'),
        'email' => Yii::t('user', 'Email'),
        'ic_number' => Yii::t('user', 'Ic Number'),
        'auth_key' => Yii::t('user', 'Auth Key'),
        'status' => Yii::t('user', 'Status'),
        'created_at' => Yii::t('user', 'Created At'),
        'updated_at' => Yii::t('user', 'Updated At'),
        'company_id' => Yii::t('user', 'Company'),
        'branch_id' => Yii::t('user', 'Branch'),
        'edu_level' => Yii::t('user', 'Education Level'),
        'position_level' => Yii::t('user', 'Position Level'),
        'designation' => Yii::t('user', 'Designation'),
        'get_mail' => Yii::t('user', 'Get Mail'),
        'date_joined' => Yii::t('user', 'Date Joined'),
        'gender' => Yii::t('user', 'Gender'),
        'address1' => Yii::t('user', 'Address1'),
        'address2' => Yii::t('user', 'Address2'),
        'address3' => Yii::t('user', 'Address3'),
        'address4' => Yii::t('user', 'Address4'),
        'country' => Yii::t('user', 'Country'),
        'state' => Yii::t('user', 'State'),
        'city' => Yii::t('user', 'City'),
        'postcode' => Yii::t('user', 'Postcode'),
        'tel_no' => Yii::t('user', 'Tel No'),
        'marital_status' => Yii::t('user', 'Marital Status'),
        'child_no' => Yii::t('user', 'Child No'),
        'race' => Yii::t('user', 'Race'),
        'religion' => Yii::t('user', 'Religion'),
        'resident_status' => Yii::t('user', 'Resident Status'),
        'bumi_status' => Yii::t('user', 'Bumi Status'),
    ];
}

public static function find()
{
    return new UserQuery(get_called_class());
}

public function getCountries()
{
    return $this->hasOne(Countries::classname(),['id'=>'country']);
}

public function getStates()
{
    return $this->hasOne(States::classname(),['id'=>'state']);
}

public function getNext_of_kin()
{
    return $this->hasMany(NextOfKin::classname(),['staff_id'=>'staff_id']);
}

}

This is my view controller

 public function actionView($staff_id)
{   
        $request = Yii::$app->request;
        $model = $this->findModel($staff_id);
        $model2 = $model ->next_of_kin;
        //$sql = "SELECT next_of_kin.name AS Name FROM user left join next_of_kin ON next_of_kin.staff_id = user.staff_id";

         $dataProvider = new ActiveDataProvider([
        'query' => User::find() ->joinWith(['next_of_kin'])-> where(['next_of_kin.staff_id' => $staff_id]),
    ]); 

    if($request->isAjax)
        {
            Yii::$app->response->format = Response::FORMAT_JSON;

            return [
                    'title'=> "User #".$staff_id,
                    'content'=>$this->renderAjax('view', [
                        'model' => $model,
                        'dataProvider' => $dataProvider,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Edit',['update','staff_id'=>$staff_id],['class'=>'btn btn-primary','role'=>'modal-remote'])
                ];    
        }
        else
        {
            return $this->render('view', [
               'model' => $model,
                'dataProvider' => $dataProvider,
                "size" => "modal-lg",
            ]);
        }
}

This is the view file

[
                'label' => 'Next of Kin Details',
                'content' => GridView::widget([
                        'dataProvider' => $dataProvider,
                        'columns' => [
                          ['class' => 'yii\grid\SerialColumn'],
                            'username',
                            'fullname',
                            'staff_id',
                            'next_of_kin.name',
                    ],
                ]),  
            ],

I trying to get the name from table next_of_kin based on the staff id inside the User table. But it keep show not set when I try to view it

3
next_of_kin is a table name? or is the name of a relation function declaredin User model? - ScaisEdge
@scaisEdge both of it. I put the same name - Ron
update your question and add the relatioal function .. for next_of_kin in User model please .. and the code where you use $dataProvider - ScaisEdge
@scaisEdge edited~ - Ron

3 Answers

0
votes

Why use array when you want to join with a single table/relation, I mean it shouldn't be wrong, but it's confusing. Your query doesn't seem wrong, look for the Database module of the debugger to see what the actual query Yii AR composed and run it in the DB in a raw form. The query itself is not broken, at least from what I can tell, DB architecture, the fact that you can query for a staff_id that has nothing to return, the way you pass $staff_id and several other stuff could be broken.

0
votes

activeDataProvider return a collection of models

you can retrieve an array of model from dataProvider

  $myModels = $dataProvider->getModels();

eg: get the first element(user model) next_of_kin models

  $my_next_of_kin = $myModels[0]->next_of_kin;

iterate over models for get a value;

  foreach ($my_next_of_kin as $key => $value) {
    echo $value->your_next_of_kin_col;
  }
0
votes

It works only with one-to-one relations! You have one-to-many.

public function getNext_of_kin()
{
    return $this->hasMany(NextOfKin::classname(),['staff_id'=>'staff_id']);
}

'columns' => [
       ['class' => 'yii\grid\SerialColumn'],
       'username',
       'fullname',
       'staff_id',
       'next_of_kin.name', // "next_of_kin" should be one-to-one relation
],