Laravel-将数据库整数转换为关联的字符串 [英] Laravel - Convert database integer to an associated string

查看:185
本文介绍了Laravel-将数据库整数转换为关联的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为status的列的用户表.在此列中,我仅根据其状态存储一个数字,1-admin,2-所有者等.我知道我可以使用{{ users->status }}显示这些值,但仅显示存储的数字.如何显示实际名称而不是存储的号码?

I have my users table with a column named status. In this column I just store a number, based off their status, 1 - admin, 2 - owner, etc. I know that I can display these values with {{ users->status }}, but only shows the stored number. How can I show the actual name instead of the stored number?

推荐答案

使用雄辩存取器变种人.

定义状态数组,并使用数据库中的状态号作为键来更改模型中的值,以便在视图中{{ $users->status }}等于admin

Define an array of statuses and use the status number from your database as a key to change the value in the model so that in the view {{ $users->status }} equals admin

class User extends Eloquent {

    protected $statuses = array(
        '1' => 'admin',
        '2' => 'owner'
    );

    public function getStatusAttribute($value)
    {
        return $this->statuses[$value];
    }

}

  • getStatusAttribute在检索记录时将1转换为admin.
    • getStatusAttribute converts 1 to admin when retrieving a record.

    • 您还可以使用set方法来确定何时将记录存储在模型中.


      You could also have a set method for when records are stored in the model.

      视图中 {{ $user->status }} // echos 'admin'

      这篇关于Laravel-将数据库整数转换为关联的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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