首页 > 其他分享 >Laravel中toArray()方法使用驼峰变量

Laravel中toArray()方法使用驼峰变量

时间:2024-02-02 16:57:40浏览次数:35  
标签:Laravel toArray 驼峰 ... value relation key attributes

前言

不知道大家在用Laravel开发过程中有没有遇到过模型查询时,with中使用驼峰命名变量名,但是使用toArray方法后,变量名变成了蛇形命名;

比如说这样的一条查询语句:

WorkflowModel::query()->with(['workflowsInfo'])->get()->toArray();

查询出来的结果可能就是这样的:

查询出来关联表的结果key变成了workflows_info这种蛇形命名方式
当然直接这样使用也是没有问题的,但是如果有需要比如说想直接使用key为workflowsInfo的情况,那有没有办法能处理呢?


使用的版本:

  • PHP: 8.1.13
  • Laravel: 10.13.5

通过查看laravel源码
web/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1636

public function toArray()
{
    return array_merge($this->attributesToArray(), $this->relationsToArray());
}

然后查看relationsToArray方法;

...
public static $snakeAttributes = true;
...
public function relationsToArray()
{
    $attributes = [];

    foreach ($this->getArrayableRelations() as $key => $value) {
        // If the values implement the Arrayable interface we can just call this
        // toArray method on the instances which will convert both models and
        // collections to their proper array form and we'll set the values.
        if ($value instanceof Arrayable) {
            $relation = $value->toArray();
        }

        // If the value is null, we'll still go ahead and set it in this list of
        // attributes, since null is used to represent empty relationships if
        // it has a has one or belongs to type relationships on the models.
        elseif (is_null($value)) {
            $relation = $value;
        }

        // If the relationships snake-casing is enabled, we will snake case this
        // key so that the relation attribute is snake cased in this returned
        // array to the developers, making this consistent with attributes.
        if (static::$snakeAttributes) {
            $key = Str::snake($key);
        }

        // If the relation value has been set, we will set it on this attributes
        // list for returning. If it was not arrayable or null, we'll not set
        // the value on the array because it is some type of invalid value.
        if (isset($relation) || is_null($value)) {
            $attributes[$key] = $relation;
        }

        unset($relation);
    }

    return $attributes;
}
...

从代码中可以看到有个公共的变量,只要将这个公共的变量设置为false,就可以不用蛇形变量,保持原有的变量名;

所以这里给出下面两种方案来处理:

方案一

使用默认不转变的方法,来实现:

...
class WorkflowModel extends BaseModel
{
    use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'workflows';

    public static $snakeAttributes = false;

    ...
}

方案二

也可以使用静态方法设置的方式来改变$snakeAttributes的变量

...
class WorkflowModel extends BaseModel
{
    use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'workflows';
    public static function setNotSnakeAttributes(): Builder
    {
        parent::$snakeAttributes = false;
        return static::query();
    }

    ...
}
WorkflowModel::setNotSnakeAttributes()->with(['workflowsInfo'])->get()->toArray();

以上就是暂时想到的两种方案,大家如果有更好的想法,可以留言一起讨论。

标签:Laravel,toArray,驼峰,...,value,relation,key,attributes
From: https://www.cnblogs.com/Sillager/p/18003207

相关文章

  • laravel生成二维码,并添加背景图片,图标logo
    1、安装组件composerrequiresimplesoftwareio/simple-qrcode1.3.*在 config/app.php 注册服务提供者:SimpleSoftwareIO\QrCode\QrCodeServiceProvider::class同样在 config/app.php 添加 QrCode 门面:'QrCode'=>SimpleSoftwareIO\QrCode\Facades\QrCode::class2......
  • laravel 跨域
    laravel怎么设置跨域(两种方法)在前后端分离的项目中,前端请求后端接口时可能会遇到跨域的问题。其中,一个典型的场景是:前端项目运行在http://localhost:8080,而后端项目运行在http://localhost:8000,这时候就需要设置跨域。在Laravel中,要设置跨域可以采用以下两种方法。1、中间......
  • laravel collect结果集group分组合并数据
    1、需求将相同apply_id的apply_remark用;拼接$r=[['apply_id'=>1,'apply_remark'=>'xxx'],['apply_id'=>1,'apply_remark'=>'xxx2'],['apply_id'=>2......
  • Java里ArrayList中的toArray()用法
    深入理解List的toArray()方法和toArray(T[]a)方法这两个方法都是将列表List中的元素转导出为数组,不同的是,toArray()方法导出的是Object类型数组,而toArray[T[]a]方法导出的是指定类型的数组。下面是两个方法的申明及说明,摘自Java8的API文档。toArray()方法的分析Object[]toA......
  • Java基础知识整理,驼峰规则、流程控制、自增自减
    写在开头本文接着上一篇文章续写哈。[Java基础知识整理,注释、关键字、运算符](https://blog.csdn.net/qq_43506040/article/details/135633325)在这一篇文章中我们总结了包括注释、关键字、运算符的Java基础知识点,今天继续来聊一聊命名规则(驼峰)、流程控制、自增自减。一、命名......
  • laravel 集合&数组
    #列表集合&数组$_list_collection=collect([['name'=>'John','age'=>25],['name'=>'Jane','age'=>30]]);$_list_array=[['name'=>'John','age......
  • 无论删除配置文件,Laravel 8在生产环境中仍无法禁用日志记录
    如果你已经在.env文件中设置了LOG_CHANNEL=null和LOG_LEVEL=null,并且在Laravel8中仍然无法禁用日志记录,可以尝试以下几个方法:phpartisanconfig:clearphpartisancache:clear这将清除配置和缓存,确保您的更改生效。检查环境:确保你正在修改正确的环境文件。在生......
  • Laravel的基本配置文件 .env 文件
    默认情况下,.env文件包含以下参数APP_ENV=localAPP_DEBUG=trueAPP_KEY=base64:ZPt2wmKE/X4eEhrzJU6XX4R93rCwYG8E2f8QUA7kGK8=APP_URL=http://www.xhcj168.comDB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=homesteadDB_USERNAME=ho......
  • laravel 419 csrf验证问题
    这次是被坑了,在linuxapache运行完好的代码放到IIS服务器上居然没有数据,检查发现居然出现了419错误,要求ajaxpost请求中应该包含csrftoken字段。然后就突然想起来了,上次相似的项目也发生过这样的问题,上次没记录,时日长久,这次居然一点儿也没想起来...按照错误提示,在ajaxpost请......
  • 使用WebStack和Laravel打造个人网址导航安装过程问题和详解记录
    前言最近测试了国内推出的多个AI大模型,为了方便记录同时方便推荐给朋友想做个AI工具网址导航。网上开源的项目有很多,最后选中了WebStack和Laravel,但是不知道是否作者长时间不更新了遇到不少问题,解决完记录一下。准备工作,购买云服务器,安装宝塔,解析域名解析等等正文1.登录宝塔创建站......