Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 gridview not showing all the left join values using hasMany retionship

Model Search :

$query = Countries::find()->joinWith(['states']);
$dataProvider = new ActiveDataProvider([
    'query' => $query,           
]);        

$dataProvider->setSort([
    'defaultOrder' => ['doc_date'=>SORT_DESC],
]);

if (!($this->load($params) && $this->validate())) {           
    return $dataProvider;
}

Model :

public function getStates()
{
    return $this->hasMany(States::className(), ['state_id' => 'state_id']);
}

I need result like

Id      Country     State
1       India       State 1
2       India       State 2
3       India       State 3
4       USA         USA State1
5       USA         USA State2

When I'm using gridview I'm getting following result

Id      Country     State
1       India       State 1
4       USA         USA State1

Please give solutions to fix this issue.

like image 243
sk2 Avatar asked May 05 '15 05:05

sk2


3 Answers

What you're seeing is the intended behavior: normally you wouldn't want your ActiveRecord query to contain duplicate primary records, so Yii filters out any duplicates caused by JOINs. You can see this behavior defined here: https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveQuery.php#L220

Since what you want is essentially to display the raw results as generated by the SQL with a JOIN (one row for each combination of Country and State), I think the most pragmatic solution would be to use the SqlDataProvider instead of the ActiveDataProvider.

This should return exactly what you want:

$query = Countries::find()->joinWith(['states'], false)->select(*);

$dataProvider = new SqlDataProvider([
    'sql' => $query->createCommand()->getRawSql(),           
]);        
like image 78
laszlovl Avatar answered Oct 23 '22 04:10

laszlovl


The answer given by laszlovl works good, but needs to change the 'query' key value by 'sql' like below:

$query = Countries::find()->joinWith(['states'], false)->select(*);

$dataProvider = new SqlDataProvider([
    'sql' => $query->createCommand()->getRawSql(),           
]);  

From the Yii 2 Docs we can find that $sql property get the SQL statement to be used for fetching data rows. The default value of this property is "null"

like image 2
Edgar Cardona Avatar answered Oct 23 '22 05:10

Edgar Cardona


If you explicitly specify the selected columns using the select() method, you can achieve the same result, without messing with raw sql queries

$query->select(['countries.*','states.*']);
like image 1
Szántó Zoltán Avatar answered Oct 23 '22 05:10

Szántó Zoltán