2

I want to display column from another table in gridview.

In my controller actionIndex:

public function actionIndex()
{     
    $user_id = \Yii::$app->user->identity->id;
    $queryFile = PowerGen::find();
    $queryFile ->select(['submitted_by','filename.file_name','filename.submitted_by'])
        ->joinWith('filename')//Tells Yii to use the complains relation that we define below. By default it is an inner join
        ->where(['filename.submitted_by' => $this->user_id]);

    $dataProvider= new ActiveDataProvider([
        'query' => $query,
        'pagination' => false,
    ]);

    return $this->render('index', ['dataProvider4'=>$dataProvider]);
}

In my model:

public function fileName()
{
    $user_id = \Yii::$app->user->identity->id;
    return $this->hasMany(Filename::className(), 'submitted_by' => $this->user_id);
}

Error is:

Error
PHP Parse Error – yii\base\ErrorException
syntax error, unexpected '=>' (T_DOUBLE_ARROW)

What is the error in the line..

Thank you

vishuB
  • 4,173
  • 5
  • 31
  • 49
Mr Second
  • 21
  • 2

3 Answers3

1

Use hasMany() like

public function fileName()
{
    $user_id = \Yii::$app->user->identity->id;
    return $this->hasMany(Filename::className(), ['submitted_by' => $this->user_id]);
}
vishuB
  • 4,173
  • 5
  • 31
  • 49
1

First i think your function must be like this:

public function fileName()
{
    return $this->hasMany(Filename::className(), ['submitted_by' => 'user_id']);
}

And your query like this:

$user_id = \Yii::$app->user->identity->id;
$queryFile = PowerGen::find();
$queryFile ->select(['submitted_by','filename.file_name','filename.submitted_by'])
                ->joinWith('filename')
                ->where(['filename.submitted_by' => $user_id]);

You are declaring the variable $user_id

$user_id = \Yii::$app->user->identity->id;

but you are not using it anywhere.

Vandro.nds
  • 442
  • 3
  • 8
0

You're defining your relation in a wrong way:

  1. Method name should be prefixed by get, like getFileName().
  2. Second argument of hasMany() should be array with map of column names. You should not use dynamic values here or model attributes.
  3. You should not use Yii::$app->user->identity->id or POST/GET data in your model. It breaks MVC pattern and will create problems if you will try to use this relation in console for example.

 

public function getFileName() {
    return $this->hasMany(Filename::className(), ['submitted_by' => 'user_id']);
}
rob006
  • 21,383
  • 5
  • 53
  • 74