【发布时间】:2016-11-12 23:39:12
【问题描述】:
我对 laravel 和受保护的 $attributes 和 mutators 有一些问题。
我有用户积分排名。我想向用户模型添加另一个具有排名位置的属性。
在用户模型中,我有这样的公共功能:
public function getRankPositionAttribute(){
$userPoints= Ranking::where('user_id','=',$this->id)->first();
$userPosition = Ranking::where('points','>',$userPoints->points)->count()+1;
return $userPosition;
}
我也设置了:
protected $attributes = array('RankPosition'='');
但它不起作用(我在属性中看不到像 RankPosition 这样的值)。奇怪的是,当我添加(例如)这样的值时:
protected $attributes =array('test'=>'yes');
Laravel 也看不到测试...
但是当我添加这个时:
protected $appends = array('RankPosition');
在我的控制器中,我找到所有用户并获得对 json 的响应,然后在 json 响应中我看到像 RankPosition 这样的值具有正确的值... :(
我做错了什么?为什么“我的 laravel”会跳过受保护的 $attributes?
请帮助我。
【问题讨论】:
-
Laravel mutators 是神奇的方法。你不会在
Model::$attributespropety 中看到你的mutator。