用一个非常简单的模型:
<?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');
}
}
为什么以下的save语句会导致使用默认值定义的字段的空属性?
$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->fresh()
重新加载模型,我会得到预期的输出:
array (size=4)
'foo' => string 'BAR' (length=3)
'abc' => null,
'status' => int 1,
'id' => int 19
有没有办法避免使用fresh
方法?在引擎盖下,新鲜是另一个数据库之旅。
答案 0 :(得分: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)。
答案 1 :(得分:0)
Eloquent Model有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