因此,我有一个名为Model
的自定义RecursiveModel
扩展类:
use Illuminate\Database\Eloquent\Model;
use ... RecursiveHelper;
class RecursiveModel extends Model {
private $recursiveHelper = null;
public function __construct(){
$this->recursiveHelper = new RecursiveHelper();
parent::__construct();
}
public function save(array $options = []){
parent::save($options);
}
...
// Additional methods available for Recursive Models (self-referenced `parent_id` relationships)
}
然后,一个Model
扩展了这个RecursiveModel
类,而不是基Model
类:
use ... RecursiveModel;
use Illuminate\Database\Eloquent\SoftDeletes;
class Line extends RecursiveModel {
use SoftDeletes;
protected $table = "lines";
protected $primaryKey = "id";
public function parent(){
return $this->belongsTo(self::class, "parent_id", "id");
}
public function children(){
return $this->hasMany(self::class, "parent_id", "id");
}
}
一切都很好,并且有了以前导入的记录(当Line
扩展了Model
而不是RecursiveModel
时,我能够使用我的RecursiveHelper
方法/逻辑没问题。现在,我正在尝试刷新数据库,该数据库称为Seeder
:
use Illuminate\Database\Seeder;
use ... Slugger;
use ... Line;
class LinesSeeder extends Seeder {
public function run(){
$parentLine = Line::create([
"name" => "Line Item",
"slug" => $this->slugger->slugify("Line Item"),
"created_at" => date("Y-m-d H:i:s"),
"updated_at" => date("Y-m-d H:i:s"),
]);
$childLine = Line::create([
"name" => "Child Line Item",
"slug" => $this->slugger->slugify("Child Line Item"),
"parent_id" => $parentLine->id,
"created_at" => date("Y-m-d H:i:s"),
"updated_at" => date("Y-m-d H:i:s"),
]);
...
}
}
如前所述,当Line
扩展了Model
而不是RecursiveModel
时,此代码可以正常工作。但是现在,我遇到了这个错误:
SQLSTATE [HY000]:常规错误:1364字段'名称'没有默认值(SQL:插入
lines
(updated_at
,created_at
)值(2018-08-13 15:56:45,2018-08-13 15:56:45))
Line::create([...]);
似乎没有收到传递的参数。扩展Model.php
时我缺少什么吗?我尝试添加:
public function create(array $options = []){
parent::create($options);
}
对于RecursiveModel
,但这只会引发另一个错误(我认为create()
方法不是Model.php
的一部分,而是Builder.php
的一部分。)< / p>
此外,protected $fillable
也不是问题,在我的'strict' => true,
连接上设置mysql
也不是问题;已经尝试过这两个都无济于事。
根据建议,将__construct
的{{1}}方法更新为:
RecursiveModel
不幸的是,仍然出现相同的错误。
编辑:public function __construct(array $attributes = []){
$this->recursiveHelper = new RecursiveHelper();
return parent::__construct($attributes);
}
有一个Line.php
方法,该方法从我逐个模型应用__construct
模型时开始沿用;解决方案是更新签名以匹配(如上所述)或从扩展模型中删除$this->recursiveHelper
。
答案 0 :(得分:3)
模型构造函数需要采用属性数组:
public function __construct(array $attributes = [])