【问题标题】:Laravel protected attributes and MutatorsLaravel 受保护的属性和 Mutators
【发布时间】: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。

标签: php laravel mutators


【解决方案1】:

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

但是当你做这样的事情时:

$user = new User;

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

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

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 2011-06-06
    • 2015-01-19
    • 2020-03-31
    • 2014-09-13
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多