【问题标题】:Eloquent create blank entriesEloquent 创建空白条目
【发布时间】:2017-09-17 02:15:38
【问题描述】:

我正在使用 Lumen (5.4) 做我的第一步,我想将一个数据数组存储到数据库中。所以,我有:

MySQL rate_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

雄辩的模型

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 属性值创建记录。但是,name,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 值时不会失败?

【问题讨论】:

    标签: mysql eloquent lumen


    【解决方案1】:

    在 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多