Mr Second
Mr Second

Reputation: 21

Yii2 Gridview error

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

Upvotes: 2

Views: 384

Answers (3)

rob006
rob006

Reputation: 22174

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']);
}

Upvotes: 0

Vandro.nds
Vandro.nds

Reputation: 452

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.

Upvotes: 1

vishuB
vishuB

Reputation: 4261

Use hasMany() like

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

Upvotes: 1

Related Questions