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 中的通用访问器和修改器 的相关文章

随机推荐

  • 从 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