Laravel 4 中的通用访问器和修改器

2024-01-06

我知道可以为各个字段定义访问器和修改器,如下所示:

public function setSomeAttribute($value) {
    // set the attribute
}
public function getSomeAttribute() {
    // return the attribute}
}

但是是否可以定义一个后备方法用于all属性的获取和设置?

原因是我想即时将任何空值转换为空值,以保持数据库干净并允许可空字段为空而不是空字符串(如果有更好的方法来做到这一点,请告诉我!)

我正在寻找类似的东西

public function setAttribute($property,$value) {
    $this->$property = empty($value) ? null : $value;
}

UPDATE:

感谢 Chris Goosey,我找到了适合我的解决方案。我扩展了 Eloquent 模型方法 setAttribute,并将该值设置为列默认值(如果该列为空)。在我的数据库中,这通常是 null、零或空字符串,所以对我来说很有效!

public function setAttribute($key, $value)
{
    // Convert empty values to their default values (e.g. null, zero)
    if(empty($value) && $this->getSchema()->hasColumn($key)) {
        $value = $this->getSchema()->getColumn($key)->getDefault();
    }
    parent::setAttribute($key,$value);
}

最好的方法可能是扩展 Eloquent 类,覆盖 setAttribute 和 getAttribute 方法。

为了使所有模型继承这些覆盖的方法,您需要创建一个扩展 eloquent 的类,例如

<?php 

class BaseModel extends eloquent {

    public function setAttribute($property,$value) {
        $this->$property = empty($value) ? null : $value;
    }

    public function getAttribute($key) {
        // Do Stuff
    }
}

然后你的所有模型都应该从这个新类扩展,例如

<?php

class User extends BaseModel {
    protected $table = 'users';
}

还值得一提的是,您的新方法应该具有旧方法的所有功能以及新功能,这就是 getAttribute() 的样子(Illuminate\Database\Eloquent 第 2212 行):

/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

同一文件中的 setAttribute 如下所示(第 2338 行):

/**
 * Set a given attribute on the model.
 *
 * @param  string  $key
 * @param  mixed   $value
 * @return void
 */
public function setAttribute($key, $value)
{
    // First we will check for the presence of a mutator for the set operation
    // which simply lets the developers tweak the attribute as it is set on
    // the model, such as "json_encoding" an listing of data for storage.
    if ($this->hasSetMutator($key))
    {
        $method = 'set'.studly_case($key).'Attribute';

        return $this->{$method}($value);
    }

    // If an attribute is listed as a "date", we'll convert it from a DateTime
    // instance into a form proper for storage on the database tables using
    // the connection grammar's date format. We will auto set the values.
    elseif (in_array($key, $this->getDates()))
    {
        if ($value)
        {
            $value = $this->fromDateTime($value);
        }
    }

    $this->attributes[$key] = $value;
}

希望这可以帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 4 中的通用访问器和修改器 的相关文章

  • 通过 Ajax 加载内容时,WORDPRESS 音频播放器未加载,MediaElement.js 未应用

    我正在创建一个 WordPress 主题 当我使用 ajax 加载内容时 它不会将 MediaElements js 应用于我的音频播放器 因此不会显示音频 我认为这是因为 MediaElement js 加载了 wp footer 并且此
  • FPDI/FPDF:水印和打印多页

    我修改了这个堆栈问题 当用户尝试下载文件时在 pdf 文件上应用水印 https stackoverflow com questions 3983432 applying watermarks on pdf files when users
  • PHP严格标准:声明应该兼容

    我有以下类层次结构 class O Base class O extends O Base abstract class A Abstract public function save O Base obj class A extends
  • posts_search 中的自定义查询

    如何使用此查询作为我的自定义搜索查询 add filter posts search my search is perfect 20 2 function my search is perfect search wp query sWord
  • 如何使用 php 下载/打印页面的特定部分

    我有一个 HTML 页面如下 Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the indust
  • 蛋糕控制台 2.2.1:烘焙错误

    运行 MAMP 的 OSX 机器 CakePHP 2 2 1 已正确安装和配置 这意味着当我浏览到 Index php 文件时 所有绿色条都显示出来 我已经完成了博客教程 并且正在开发我的第二个应用程序 其中脚手架已启动并运行 现在我第一次
  • 交换关联数组中的两个项目

    Example arr array apple gt sweet grapefruit gt bitter pear gt tasty banana gt yellow 我想调换一下柚子和梨的位置 这样数组就变成了 arr array ap
  • PHP 在输入流中使用 fwrite 和 fread

    我正在寻找将 PHP 输入流的内容写入磁盘的最有效方法 而不使用授予 PHP 脚本的大量内存 例如 如果可以上传的最大文件大小为 1 GB 但 PHP 只有 32 MB 内存 define MAX FILE LEN 1073741824 1
  • 在 PHP 中使用 phpseclib 时出现 RSA 问题

    我正在尝试在 phpseclib 中使用 RSA 实现 我认为在函数中执行一次代码并重新使用该函数会更容易 当我尝试向代码发送短信时 我收到一条错误消息 提示 解密错误 测试还让我意识到每次代码运行时密文都是不同的 所以我显然在那里做错了什
  • jQuery Mobile 表单验证

    我有一个移动网站 除了验证之外一切都工作正常 基本上我希望从用户那里获取值 然后在单独的页面 process php 上处理它们 但是 在这样做之前 我需要检查以确保字段已填充 我已经研究了几种方法来做到这一点 但似乎没有一种有效 我现在有
  • 使用 Ajax.Request 将 JSON 从浏览器传递到 PHP 的最佳方法

    您好 我有一个 JSON 对象 它是一个二维数组 我需要使用 Ajax Request 将其传递给 PHP 我知道的唯一方法 现在我使用js函数手动序列化我的数组 并获取以下格式的数据 s 1 d 3 4等 我的问题是 有没有办法更直接 有
  • 跟踪用户何时点击浏览器上的后退按钮

    是否可以检测用户何时单击浏览器的后退按钮 我有一个 Ajax 应用程序 如果我可以检测到用户何时单击后退按钮 我可以显示适当的数据 任何使用 PHP JavaScript 的解决方案都是优选的 任何语言的解决方案都可以 只需要我可以翻译成
  • SQL 最近日期

    我需要在 php 中获取诸如 2010 04 27 之类的日期作为字符串 并在表中找到最近的 5 个日期 表中的日期保存为日期类型 您可以使用DATEDIFF http dev mysql com doc refman 5 1 en dat
  • 表单提交后如何保留选择字段中的选定值?

    我有一个用于将票证上传到数据库的主页 我有一个选择字段 我想保留用户在提交表单之前选择的值 但它没有发生 这是我选择字段的代码
  • php 错误 fopen(): 文件名不能为空

    发送带有附件代码的电子邮件工作正常 最近我们已将文件传输到另一个托管服务器 idk 发生了什么 它显示以下错误 警告 fopen 第 106 行 home hugerecruitmetnt public html validatecva p
  • Doctrine EntityManager 清除嵌套实体中的方法

    我想用学说批量插入处理 http doctrine orm readthedocs org en latest reference batch processing html为了优化大量实体的插入 问题出在 Clear 方法上 它表示此方法
  • 内部 while 循环不工作

    这是我项目网页上的代码片段 这里我想显示用户选择的类别 然后想显示属于该类别的主题 在那里 用户可以拥有多个类别 这没有问题 我可以在第一个 while 循环中打印所有这些类别 问题是当我尝试打印主题时 结果只显示一行 但每个类别中有更多主
  • 如何在 Laravel 中使用 PUT http 动词提交表单

    我知道这个问题可能已经提出 但我就是无法让它发挥作用 如果有人可以帮助我 我将非常感激 我安装了 colletive form 但答案也可以是 html 表单标签 现在列出我的表格 我的路线和我的例外情况 Form model array
  • ini_set 'session.gc_maxlifetime' 为 1 天

    If I do ini set session gc maxlifetime 86400 这是否意味着用户可以将浏览器留在同一页面 非活动状态 最多 1 天 而不必担心会话被垃圾收集并被注销 如果服务器配置不支持此功能会发生什么 它会给我一
  • 如何使用 PHPExcel 库从 Excel 获取日期

    我正在尝试使用 PHPExcel 从 Excel 获取日期 但我没有得到日期 我得到的字符串值不是 1970 以来的秒数 我尝试过的代码是 InvDate trim excel gt getActiveSheet gt getCell B

随机推荐

  • 从 UUID 版本 1 获取 UNIX 时间戳

    在我们的 Java 应用程序中 我们尝试从 UUID 获取 UNIX 时间版本1 https en wikipedia org wiki Universally unique identifier Version 1 date time a
  • 将 List 传递给 String... 参数

    我正在努力将字符串列表传递到需要参数的方法中 细绳 有人可以帮我吗 How to put names into dummyMethod List
  • Netbeans 新建项目向导不显示 Maven Web 应用程序

    我已经阅读了与此相关的其他问题 所以这不是另一个重复 在 Netbeans 8 0 中使用 新建项目向导 时 我选择Maven但我无法选择Web应用程序 它根本不显示 所以我问谷歌 它告诉我安装JAVA EE And I did但 Mave
  • 在 Google Colab Notebook 中提供 Iframe:本地主机拒绝连接

    我正在尝试使用以下内容从 Google Colab 笔记本提供一些 HTML from IPython display import IFrame IFrame src output index html width 700 height
  • 如何在相关实体中搜索(Hibernate 搜索)

    我没有尝试这个东西 我的要求是按名称搜索记录 以下是我的相关课程 记录文件夹分析 java Indexed public class RecordFolderAnalysis extends AuditableEntity implemen
  • 继承最佳实践:*args、**kwargs 或显式指定参数 [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我经常发现自己覆盖了父类的方法 并且永远无法决定是否应该显式列出给定的参数或仅使用毯子 args kwargs构造 一个版本比另一个版本更好吗
  • XAML / cs - 更新包后成员名称不能与其封闭类型 (CS0542) 相同

    我刚刚更新了应用程序中的软件包 并且收到了许多我不理解的此类新错误 Users alan Downloads Japanese 31 Japanese obj Debug Views Help GettingStarted xaml g c
  • SQL在删除子表行时锁定父表

    TLDR 当尝试通过 子 表上的主键删除包含另一个 父 表的外键的行时 它会在子事务的持续时间内锁定父表 如何使用外键 子删除来防止发生锁定 示例场景 Setup IF SELECT OBJECT ID dbo Child IS NOT N
  • 处理序列化框架的不兼容版本更改

    问题描述 我们有一个 Hadoop 集群 在该集群上存储使用以下命令序列化为字节的数据Kryo http code google com p kryo 序列化框架 我们用来执行此操作的 Kryo 版本是从官方版本 2 21 分叉出来的 以便
  • Kotlin 和 Android 中“没有足够的信息来推断参数 T”

    我正在尝试使用 Kotlin 在我的 Android 应用程序中复制以下 ListView https github com bidrohi KotlinListView https github com bidrohi KotlinLis
  • 准确确定 Python 多处理期间腌制的内容

    正如线程中所解释的当我调用 multiprocessing Process 时正在腌制什么 https stackoverflow com questions 26025878 what is being pickled when i ca
  • 将数据分组为模糊间隙和孤岛

    这本质上是一个间隙和岛屿问题 但它是非典型的 我确实将示例缩减到最低限度 我需要识别超过特定阈值的间隙 并且重复不会成为问题 尽管此示例删除了它们 在任何情况下 使用 ROW NUMBER 的常见解决方案都没有帮助 因为即使是 1 的间隙也
  • 构建应用程序后,Electron index.html 未加载

    我有一个电子应用程序 在与它捆绑之前运行得非常好electron builder 捆绑并打开应用程序后 出现以下错误 Not allowed to load local resource file tmp mount displa4VwuQ
  • 产品属性的数据库架构

    我想在类别中实现产品过滤 并且对正确的数据库架构有疑问 现在我有下表 类别 1 id 2 category 3 description Products 1 id 2 category id 3 product 4 image 5 pric
  • UDID 和 UUID 之间的区别[重复]

    这个问题在这里已经有答案了 有人说UDID Unique Device IDentifier 有人说UUID Universally Unique IDentifier 它们是否相同 它们之间有什么区别 UUID 通用唯一标识符 以每个应用
  • 闭包中局部变量的错误行为

    我被下面的代码困住了 首先 我将描述用例 使用 ColorGradient 实例调用函数 addPreset 打电话时this listController addItem 名为的回调函数onSelect是提供的 每次触发 listCont
  • 错误:useHref() 只能在 组件的上下文中使用

    当我直接在我的路由器组件中写入我的导航栏组件内容时 它工作正常 但是当我在导航栏组件中写入该内容时 它会生成以下错误 错误 useHref 只能在组件上下文中使用 我在用着 react dom 17 0 2 react router dom
  • 使用 clang 编译时 openmp 无法正确链接

    我已经在 Ubuntu 16 04 上从源代码构建了 clang 4 0 并尝试编译一个简单的 OpenMP 程序 但收到以下错误 tmp test 7f2c7c o In function main home me sf shared t
  • 选择两列之间的日期

    我需要一个 SQL 查询 如果我有两列STARTDATE and END DATE 我想选择日期位于这两个日期之间的所有行 例如 开始日期 1 1 2011 且结束日期 2 2 2011 SELECT FROM table1 WHERE 2
  • Laravel 4 中的通用访问器和修改器

    我知道可以为各个字段定义访问器和修改器 如下所示 public function setSomeAttribute value set the attribute public function getSomeAttribute retur