Yii Framework ist really great, but I encountered a problem when using Active Record for querying data from MySQL database.
When I join 2 tables (‘building’ and ‘building_info’) in my Function “get” in model Building, there will be no data returned from my second table. If I execute the same query with Query Class, rows from both table will be returned. With Active Record I only get data from table ‘building’.
Model Building:
...
// Setting Relation
public function getBuildingInfos()
{
return $this->hasMany(BuildingInfo::className(), ['BuildingID' => 'ID']);
}
// Get all buildings
public function get() {
$building = Building::find()
->joinWith('buildingInfos')
->where(['building_info.langID' => 1])
->all();
return $building;
}
// Attributes
public function attributeLabels()
{
return [
'ID' => 'ID',
'NameBreak' => 'Name Break',
'Tileset' => 'Tileset',
'TilesetPosition' => 'Tileset Position',
...
]
}
...
Model BuildingInfo:
...
public function attributeLabels()
{
return [
'buInfoID' => 'Bu Info ID',
'BuildingID' => 'Building ID',
'langID' => 'Lang ID',
'Name' => 'Name',
'ShortDesc' => 'Short Desc',
'ShortDescDisabled' => 'Short Desc Disabled',
];
}
public function getBuilding()
{
return $this->hasOne(Building::className(), ['ID' => 'BuildingID']);
}
...
Controller (GameController.php), I call this Controller by AJAX Request
class GameController extends Controller
{
...
public function actionBuilding()
{
$building = new Building();
$buildings = $building->get();
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $buildings;
}
...
}
As I mentioned above, If I execute the select statement including left join with the DB\Query Class, then the related data will be returned (but all data types lost):
Probably you have to convert each ActiveRecord object to an associative array before you return the results.
The following is a rough understanding of mine regarding the JSON formatting in the response.
When the response format is JSON and the content of it is not specified yet, the response component will try to convert the data into a JSON string using Json:encode(). Basically it will do so by serializing an associative array to a string. When given an object instead of an array, it will try to convert the object to an array when the object is arrayable. A Model is arrayable, so the ordinary attributes are converted into the elements of an array. But, the relations are not arrayable, I guess. That’s why you don’t get the relational data in the final output of JSON.
Please make a correction if I’m wrong > @anyone who has a clear understanding regarding this.