Laravel模型条件格式 [英] Laravel Model conditional formatting

查看:88
本文介绍了Laravel模型条件格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Vote_actions的数据库和模型,如下所示:

I have a database and model called Vote_actions that looks like this:

  • id
  • group_id
  • user_id
  • action_type
  • 匿名(布尔值)

用户可以要求匿名(这将使布尔值成为true).如果是这种情况,我想将group_id和user_id从返回的模型更改为-1.

User can ask to be anonymous (that would make the boolean value to be true).If that is the case, I want to change the group_id and user_id from the returned model to -1.

laravel中有什么方法可以做到吗?

Is there a way in laravel that I can do it ?

推荐答案

您倾向于特殊情况下的边缘情况.

You are leaning towards an edge case, with special conditions.

使用访问器:

class VoteActions extends \Eloquent {

    public $casts = [
        'anonymous' => 'boolean'
    ];
    ...

    /**
    * Accessors: Group ID
    * @return int
    */
    public function getGroupIdAttribute()
    {
        if((bool)$this->anonymous === true) {
            return -1;
        } else {
            return $this->group_id;
        }
    }

    /**
    * Accessors: User ID
    * @return int
    */
    public function getUserIdAttribute()
    {
        if((bool)$this->anonymous === true) {
            return -1;
        } else {
            return $this->user_id;
        }        
    }
}

官方文档: https://laravel.com/docs/5.1 /eloquent-mutators#accessors-and-mutators

但是,我建议您在必要时将数据库中的值直接设置为-1,以保持应用程序的完整性.

However, i would recommend that you set the value in the database directly to -1 where necessary so as to preserve the integrity of your application.

这篇关于Laravel模型条件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆