Yii2其余字段
问题描述:
使用GET列出记录时,包含的extraField显示正确的值 - rate_increase是额外的字段。Yii2其余字段
{
"reseller_rateref": 263756,
"rate_increase": "50.00",
...
},
模型
class ResellerRateResource extends ResellerRate
{
public $rate_increase;
/*
* @return $fields array Filtered fields for API presentation
*/
public function fields()
{
$fields = array_merge(parent::fields(), ['rate_increase']);
return $fields;
}
查询来获取数据:
$query = $model::find()
->leftJoin('reseller_config', 'reseller_rate.resellerref = reseller_config.resellerref')
->select('reseller_rate.*, reseller_config.rate_increase AS rate_increase');
然而观看单个记录时,它始终显示为空。任何人都知道为什么?
答
我敢肯定,这条线是错误的:
$fields = array_merge(parent::fields(), ['rate_increase']);
什么是['rate_increase']
?你刚刚定义的一个数组,它包含一个字符串值。
我认为你需要一些$variable['rate_increase']
然后它可能会工作。
答
据我所知fields
只用于查看目的隐藏敏感信息。但是,如果您有任何动态属性,在自定义查询,你可以使用属性函数来获得属性的值:
function attributes() {
$attrs = parent::attributes(); // get all the attributes of the current model
$attrs[] = 'rate_increase';
return $attrs;
}
现在,当你永远有一个值rate_increase
列,你将得到的值,例如:$model->rate_increase
;
http://www.yiiframework.com/doc-2.0/yii-base-model.html#attributes()-detail
不,我们不这样做,因为你没有提供的信息 – delboy1978uk
更好.... – Kyle
是的,看到我的回答 – delboy1978uk