Hi,
$provider = new ActiveDataProvider([
'query' => Major::find()->select('id, name_cn AS name')->where(['like', 'name_cn', Yii::$app->getRequest()->get('q', '')]),
'pagination' => [
'pageSize' => $this->page_limit,
],
]);
return [
'items' => $provider->getModels(),
'total_count' => $provider->getTotalCount(),
'limit' => $this->page_limit,
];
the runned sql:
SELECT `id`, `name_cn` AS `name` FROM `major` WHERE `name_cn` LIKE '%ra%' LIMIT 10
the result:
{"items":[{"id":30467},{"id":30468},{"id":30469},{"id":30470},{"id":30471},{"id":30472},{"id":30473},{"id":30474},{"id":30475},{"id":30476}],"total_count":2422}
there is no name attribute returned.
I change this:
$provider = new ActiveDataProvider([
'query' => Major::find()->select('id, name_cn')->where(['like', 'name_cn', Yii::$app->getRequest()->get('q', '')]),
'pagination' => [
'pageSize' => $this->page_limit,
],
]);
return [
'items' => $provider->getModels(),
'total_count' => $provider->getTotalCount(),
'limit' => $this->page_limit,
];
returned:
{"items":[{"id":30467,"name_cn":"\u516c\u8def\u8fd0\u8f93\u4e0e\u7ba1\u7406"},{"id":30468,"name_cn":"\u9ad8\u7b49\u7ea7\u516c\u8def\u7ef4\u62a4\u4e0e\u7ba1\u7406"},{"id":30469,"name_cn":"\u8def\u653f\u7ba1\u7406"},{"id":30470,"name_cn":"\u6c7d\u8f66\u8fd0\u7528\u6280\u672f"},{"id":30471,"name_cn":"\u4ea4\u901a\u5b89\u5168\u4e0e\u667a\u80fd\u63a7\u5236"},{"id":30472,"name_cn":"\u57ce\u5e02\u4ea4\u901a\u8fd0\u8f93"},{"id":30473,"name_cn":"\u516c\u8def\u76d1\u7406"},{"id":30474,"name_cn":"\u9053\u8def\u6865\u6881\u5de5\u7a0b\u6280\u672f"},{"id":30475,"name_cn":"\u5de5\u7a0b\u673a\u68b0\u63a7\u5236\u6280\u672f"},{"id":30476,"name_cn":"\u5de5\u7a0b\u673a\u68b0\u8fd0\u7528\u4e0e\u7ef4\u62a4"}],"total_count":2422,"limit":10}
How can i handle this?
Thanks!
If you use ActiveRecord the model must have the property for it to be populated.
If you add public $name to your Major model this would work.
@Alex-Code
Yes, the model extends from ActiveRecord.
I add public $name, but no use.
@qiangxue 大大
It should work if you add public $name to Major. Please double check. If not, please set a breakpoint in BaseActiveRecord line 1046 and see why.
Thanks! @Alex-Code & @qiangxue
I got the reason.
Because the Major is extended from ActiveRecord.
When Response process the returned data to json data,it will call the Major model's toArray function, and it will try to resolve fields.
Finally will call BaseActiveRecord::fields() but not Model::fields() 「this will get public properties by default」.
So set public $name is not work to my scenario, I should inherit the fields function in Major to join name to field list.