【问题标题】:Why are Laravel eloquent model attributes based on default definitions empty after save?为什么保存后基于默认定义的 Laravel eloquent 模型属性为空?
【发布时间】:2016-06-11 06:24:38
【问题描述】:

使用非常简单的模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{

}

这是完整的架构:

<?php

use App\Models\Lease;
use App\Models\Choice;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableExamples extends Migration {

    public function up()
    {
        Schema::create('example', function(Blueprint $table)
        {
            $table->increments('id');
            $table->enum('status', [1, 2, 3])->default(1);
            $table->text('abc')->nullable();
            $table->text('foo')->nullable();
        });
    }

    public function down()
    {
        Schema::dropIfExists('example');
    }
}

为什么以下保存语句会导致使用默认值定义的字段的属性为空?

$example1 = new App\Models\Example();
$example1->foo = "BAR";
$example1->save();

var_dump($example1->attributes);

这会输出以下内容,请注意输出已跳过状态字段。另请注意,缺少字段 abc

array (size=4)
    'foo' => string 'BAR' (length=3)
    'id' => int 19

如果我使用$example1-&gt;fresh() 重新加载模型,我会得到预期的输出:

array (size=4)
    'foo' => string 'BAR' (length=3)
    'abc' => null,
    'status' => int 1,
    'id' => int 19

有没有办法避免fresh 方法?在引擎盖下,fresh 是数据库的另一次旅行。

【问题讨论】:

    标签: php laravel laravel-5.1


    【解决方案1】:

    您可以尝试按照其他帖子中的建议另外(或专门)在模型中设置默认值:How to set a default attribute value for a Laravel / Eloquent model?

    这适用于我的 Laravel 5.1 安装:

    class Example extends Model
    {
        protected $attributes = [
            'status' => 1
        ];
    }
    

    但是,如果您将数据库视为唯一的事实来源(并在那里设置默认值),则从中获取新实例可能更安全。如果您查看 Eloquent 的 save(),您会发现它不会获取更新/插入的记录(并且 afaik,一些数据库作为 mysql 不支持在单个调用中插入/更新时返回记录- you might use a stored procedure though)。

    【讨论】:

      【解决方案2】:

      Eloquent 模型有 getOriginal() 方法,它返回模型的原始属性值。

      刚刚对其进行了测试,它会返回所有带有值的列。所以它会是:

      $example1 = new App\Models\Example();
      $example1->foo = "BAR";
      $example1->save();
      
      var_dump($example1->getOriginal());
      

      https://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_getOriginal

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-15
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-20
        • 2014-06-17
        相关资源
        最近更新 更多