gpt4 book ai didi

php - Laravel - 模型以空属性值(NULL)保存到数据库

转载 作者:行者123 更新时间:2023-12-04 01:47:42 30 4
gpt4 key购买 nike

我尝试将我的模型保存到数据库中。该模型已保存到数据库中,但未设置属性值并保持为空。

enter image description here

这是一个只有几个属性的小模型:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Unit extends Model
{
public $fillable = ['name', 'description', 'created_at', 'updated_at'];

protected $table = 'units';

// Allowed fields from forms
// protected $guarded = ['ic'];

/**
* @var string
*/
public $name = NULL;

/**
* @var string
*/
public $description = NULL;
}

Controller 存储函数:

/**
*
* @param Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate(request(), [
'name' => 'required|max:80|regex:/^[\pL\s\-]+$/u', //regex: only allows letters, hyphens and spaces explicitly',
'description' => 'required',
'image' => 'required|image',
]);

$unit = new Unit();

$unit->description = $request->description;
$unit->name = $request->name;

echo $unit->description . PHP_EOL; //Outputs "example description"
echo $unit->name . PHP_EOL; //Outputs: "example name"

$unit->save();
...

我很困惑,它应该工作。我做错了什么?

更新:

save()之后的对象$unit:

Unit {#190 ▼
+fillable: array:2 [▼
0 => "name"
1 => "description"
]
#table: "units"
+name: "example name"
+description: "example description"
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#perPage: 15
+exists: true
+wasRecentlyCreated: true
#attributes: array:3 [▼
"updated_at" => "2017-03-01 10:18:59"
"created_at" => "2017-03-01 10:18:59"
"id" => 27
]
#original: array:3 [▼
"updated_at" => "2017-03-01 10:18:59"
"created_at" => "2017-03-01 10:18:59"
"id" => 27
]
#casts: []
#dates: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▼
0 => "*"
]
}

最佳答案

删除这个:

   /**
* @var string
*/
public $name = NULL;

/**
* @var string
*/
public $description = NULL;

关于php - Laravel - 模型以空属性值(NULL)保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42528799/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com