when performing a query with relational data and eager loading such as
$query = Track::find()
->with('owners')
->where( ['public' => 1] )
->orderBy( ['creation_date' => SORT_DESC] )
->limit( 10 )
->all();
the relational data is not returned in the resulting JSON object.
Did you try ->asArray()->all()?
with the hours of searching you'd think that this could have been easier to find. FFS.
Could you show var_dump($query) and the resulting JSON?
your asArray() suggestion worked. i spent hours crawling the web for a solution and nowhere is anything like this posted. thanks.
@samdark is it an expected behavior?
Checked once more. Yes, it is.
Yes. It's expected: http://www.yiiframework.com/doc-2.0/guide-rest-resources.html
i see how it's supposed to work. and i completely understand that the client should be able to determine what related objects are returned. however i find it a bit strange that there is no simple way for the server to enable serializing of all related objects. in the current system the client MUST list all of the required related objects in the 'expand' request field.
for simplicity my goal is to make a simple request that inherently requires several related objects to be returned. i am forced to build the output object myself using toArray:
$tracks = Track::find()
->joinWith( ['owners', 'sources', 'userVoteState'], true )
->where( ['public' => 1] )
->orderBy( ['creation_date' => SORT_DESC] )
->limit( 10 );
->all();
$output = array();
foreach( $tracks as $track )
{
$trackOutput = \yii\helpers\ArrayHelper::toArray( $track );
$trackOutput['owners'] = \yii\helpers\ArrayHelper::toArray( $track->owners );
$trackOutput['sources'] = \yii\helpers\ArrayHelper::toArray( $track->sources );
$trackOutput['userVoteState'] = intval( $track->userVoteState['state'] );
$trackOutput['siteActions'] = $track->getSiteActions( $track->owners );
array_push( $output, $trackOutput );
}
return $output;
i suppose i could also modify the request fields. however both solutions feel a bit hacky. but whatever - it works.
Also issue with ActiveDataProvider. With this we can't use asArray()!!
Most helpful comment
Did you try
->asArray()->all()?