Laravel保护属性和Mutators



我对laravel和受保护的$属性和mutator有一些问题。

我有用户排名与积分。我想添加到用户模型与排名位置的另一个属性。

在用户模型中,我有这样的公共函数:

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也没有看到test…

但是当我加上这个:

protected $appends = array('RankPosition');

和在我的控制器中,我找到所有用户并获得json响应,然后在json响应中,我看到像RankPosition这样的值与正确的值…(

我做错了什么?为什么"我的laravel"跳过受保护的$属性?

请帮帮我。

这是因为如果你在类中提供protected $attributes,那么当属性的来源是表时,Laravel不会覆盖它。这里$attributes的来源是数据库列。

但是当你这样做的时候:

$user = new User;

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

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

最新更新