i have two table one is app table the other is user table both has column named name.
now i run following code:
$query = User::find()->select(['user.name','app_name' => 'app.name', 'user.create_time', 'app_id'])->innerJoinWith('app')->where(['permission_level' => 0, 'parent_id' => $id])->andWhere(['LIKE', 'user.name', $uname])->andWhere(['LIKE', 'app.name', $aname])->all();
The $query only has 3 columns which is name, create_time, app_id. why the app_name column is missing? can anyone help me. Thank you.
I replace above code with this one utilizing query only, the result is what i want as four columns appears correctly. Anyone can tell me what's wrong with my above code. Thank you.
$query = (new Query)->select(['uname' => 'user.name', 'aname' => 'app.name', 'user.create_time', 'app_id'])->from('user')->innerJoin('app', 'user.app_id = app.id')->where(['permission_level' => 0, 'parent_id' => $id])->andWhere(['LIKE', 'user.name', $uname])->andWhere(['LIKE', 'app.name', $aname])->all();
try use asArray()->all()
Thanks @mdmunir. Your solution also works. Do you know why this happens? And the other thing is if i print out $query->app, there is nothing inside. but i have do the relation mapping in the User model like this:
public function getApp() {
return $this->hasOne(App::className(), ['id' => 'app_id']);
}
after i add asArray() the json_encode result of $query is [{"name":"[email protected]","app_name":"ionic","create_time":"1419406188","app_id":"1","app":{"id":"1","name":"ionic","access_key":"$2y$13$qc/4Dxhkn5YZWlwfjWMuPOdOJZfd008mB3DLM2YoW7JvLCxzH463u","access_token":"","create_time":"1417832945","update_time":"1417832945"}},{"name":"[email protected]","app_name":"masPreviewer","create_time":"1422254640","app_id":"25","app":{"id":"25","name":"masPreviewer","access_key":"$2y$13$OD0aCAYHz9rfEVmYtn0DjuJn2B314NX/vZpux9AJ/XnrdAlWslZpW","access_token":"","create_time":"1422254635","update_time":"1422254635"}}]
From above case i can see that the object way does not work but the array way does. Why...
if you select a column name that does not exist in the model, you have to create a property in the model for it.
@myc0210 http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#selecting-extra-fields i hope this helps to explain how you can handle extra columns.
Most helpful comment
try use
asArray()->all()