我正在使用 Lumen (5.4) 执行第一步,我想将数据数组存储到数据库中。所以,我有:
MySQLrate_plans表
id PK AUTO_INCREMENT
name VARCHAR(45) NOT_NULL
slug VARCHAR(45) NOT_NULL
price FLOAT(5,2) NOT_NULL
created_at DATETIME NOT_NULL
updated_at DATETIME NOT_NULL
Eloquent 模型
use Illuminate\Database\Eloquent\Model as Model;
class RatePlan extends Model {
protected $table = 'rate_plans';
protected $dateFormat = 'Y-m-d H:i:s';
protected $fillable = ['name', 'price'];
protected $guarded = [];
}
问题是,Eloquent 使用正确的 id、created_at 和 Updated_at 属性值创建记录。但是,名称、slug 为空,价格为 0.00。代码是:
$data = ['name' => 'Test', price => 99.99];
$model = new \App\Models\RatePlan();
$model->fill($data);
$model->slug = 'test';
$model->status = 'active';
$model->create();
有什么想法吗?为什么 Eloquent 在持久化 null 值时不会失败?
最佳答案
在 Laravel 中有两种创建相关模型的方法( source )
- 创建()
- 保存()
您可以使用其中任何一个。要了解两种方法之间的差异,请参阅link
在您的代码中,您可以像这样更改它
$data = ['name' => 'Test', price => 99.99];
$model = new \App\Models\RatePlan();
$model->fill($data);
$model->slug = 'test';
$model->status = 'active';
$model->save();
或者您可以在 $data
数组中传递 slug
的值,然后像这样继续:
$data = [name => 'Test', slug => 'test',price => 99.99];
$model = new \App\Models\RatePlan();
$model->create($data);
关于mysql - Eloquent 创建空白条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260033/