繁体   English   中英

Laravel保护属性和Mutators

[英]Laravel protected attributes and Mutators

我对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”跳过保护$属性?

请帮我。

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

但是当你做这样的事情:

$user = new User;

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM