Laravel受保护的属性和变形器

4

我有一些关于Laravel中protected $attributes和mutators的问题。

我有一个用户积分排名。我想在User模型中添加另一个属性来表示排名位置。

在User模型中,我有以下公共函数:

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::$attributes 属性中看到你的 mutator。 - Skysplit
1个回答

2
这是因为如果您在类中提供了protected $attributes,那么当属性的来源是表格时,Laravel不会覆盖它。这里$attributes的来源是数据库列。
但是,当您执行以下操作时:
$user = new User;

然后你会看到一个test属性。

因此,为了动态添加属性,您应该在模型上使用appends属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接