雄辩地不允许下划线开头的字段 [英] Eloquent not allowing fields starting with an underscore

查看:86
本文介绍了雄辩地不允许下划线开头的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

口才明确拒绝以下划线开头的字段/列



https://github.com/laravel/framework/blob/7212b1e9620c36bf806e444f6931cf5f379c68ff/src/Illuminate/Database/Eloquents/Concerns。 php#L154



在这里介绍



https://github.com/laravel/framework/commit/1000e2dca7f42d5cd5e03cbdc85fcf957bbbb$5$a

看来,解决此问题的唯一方法是手动将每个下划线列指定为可填充或将其设置为不加保护为true。



是否有任何原因?我能想到的唯一原因就是系统中的前缀 _ 意味着一个私有变量,而不是放入DB中?当下划线是SQL中的有效列前缀时,看起来似乎很奇怪。

解决方案

我认为这是因为Eloquent使用魔术。这样做时,它必须强制执行命名约定,以确保不会出现不必要的错误。



例如,看看 Eloquent\Model\Concerns\HasAttributes ,您将看到 Str :: studly 来定义变量。



如果Eloquent允许定义 foo_column _foo_column ,都将具有相同的变量函数 getFooColumn 。这会导致很多问题。例如,为 foo_column 定义一个变量会同时遮盖 _foo_column


Eloquent explicitly rejects fields/columns starting with an underscore

https://github.com/laravel/framework/blob/7212b1e9620c36bf806e444f6931cf5f379c68ff/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php#L154

It was introduced here

https://github.com/laravel/framework/commit/1000e2dca7f42d5cd5e03cbdc85fcf957b7a5548

It seems the only way around this is to manually specify each underscore column as fillable or set unguarded to be true.

Is there any reason for this ? Only reasons I can think would be a system where prefixing _ means a private variable and not put in the to DB ? Seems odd when underscore is a valid column prefix in SQL

解决方案

I think it is because Eloquent uses magic. As it does, it must enforce conventions on naming to ensure no unnecessary bugs appear.

For instance, take a look at the code of Eloquent\Model\Concerns\HasAttributes and you will see it using Str::studly to define mutators.

If Eloquent allows defining foo_column and a _foo_column, both will have the same mutators functions getFooColumn. This can lead to many problems. For example, defining a mutator for foo_column will shadow _foo_column also.

这篇关于雄辩地不允许下划线开头的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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