Laravel使用Casts转换类型

3 篇文章 0 订阅

本文主要用于记录学习,具体操作建议查看更加详细的官方文档。传送门

本文只记录了其中一部分常用的用法。

文中 demo 来自官方文档。

前言

有时候,数据库里取出的数据,需要我们手动处理相应格式。

比如,某个字段存储的是 json,那么在 orm 取出数据后,手动再 json_encode,处理成我们可识别的样子。

默认的格式类型

官方文档中,明确指出了目前已经定义的类型。传送门

  • integer
  • real
  • float
  • double
  • decimal:<digits> 例如:decimal:2
  • string
  • boolean
  • object
  • array
  • collection
  • date
  • datetime
  • timestamp
  • encrypted
  • encrypted:object
  • encrypted:array
  • encrypted:collection

自定义格式类型

官方文档:传送门

操作步骤:

  • php artisan make:cast Json

  • 完善 Json@setJson@get

    <?php
    
    namespace App\Casts;
    
    use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
    
    class Json implements CastsAttributes
    {
        /**
         * Cast the given value.
         *
         * @param  \Illuminate\Database\Eloquent\Model  $model
         * @param  string  $key
         * @param  mixed  $value
         * @param  array  $attributes
         * @return array
         */
        public function get($model, $key, $value, $attributes)
        {
            return json_decode($value, true);
        }
    
        /**
         * Prepare the given value for storage.
         *
         * @param  \Illuminate\Database\Eloquent\Model  $model
         * @param  string  $key
         * @param  array  $value
         * @param  array  $attributes
         * @return string
         */
        public function set($model, $key, $value, $attributes)
        {
            return json_encode($value);
        }
    }
    
  • 使用 Json::class

    <?php
    
    namespace App\Models;
    
    use App\Casts\Json;
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model
    {
        /**
         * The attributes that should be cast.
         *
         * @var array
         */
        protected $casts = [
            'options' => Json::class,
        ];
    }
    

最后

casts 的用法还有很多,目前这些已经符合了我当前的使用场景,后续使用到继续补充。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值