我对laravel和protected $ 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”跳过保护$属性?
请帮帮我。
答案 0 :(得分:2)
这是因为如果您在班级中提供protected $attributes
,那么当属性源是表格时,Laravel不会覆盖它。这里$attributes
的来源是数据库列。
但是当你做这样的事情时:
$user = new User;
然后您会看到test
属性。
因此,要动态添加属性,您应该在模型上使用appends
属性。