【发布时间】:2017-08-14 19:07:53
【问题描述】:
我在 Laravel (第一个项目)非常新手,所以如果我犯了新手错误,请多多包涵。我正在尝试在运行 Laracasts 时创建这个项目,所以我正在使用他的建议。我正在使用 Laravel 5.4 和 PHP 7.1.4
我在布尔字段的表单上有一个复选框。如果在提交表单时未选中复选框,则返回 null。我不想要布尔值的空值,所以我有一个验证器确保它只接受真/假值。为了使它工作,我必须创建一个修改器来将值更改为 false(如果它为空)。
我有两个模型,Item 和 ItemNote。我正在尝试从 Item 模型创建 ItemNote。在Item页面有一个添加ItemNote的地方,它贯穿到ItemNoteController,然后我在Item中调用一个方法来添加ItemNote。问题是我无法让修改器在 ItemNote 模型中运行,因此验证失败,因为布尔字段 (calendar_item) 为空。
我最初试图从与 Item 的关系中创建 ItemNote,根据此堆栈溢出 Laravel 5 mutators only work when I create a record and not when I update a record 回答通过关系 $this->notes()->create($request- >所有())。您必须使用模型 $this->notes->create($request->all()) 注意注释后没有括号。所以我已经尝试了所有我能想到的方法来尝试通过模型创建对象,但我仍然无法让 mutator 运行。
这是我的模型中的关系声明:
物品
public function notes() { return $this->hasMany(ItemNote::class); }
物品备注
public function item() { return $this->belongsTo(Item::class); }
在 ItemNote 中为 calendar_item 修改器
protected function setCalendarItemAttribute($value) { $this->attributes['calendar_item'] = isset($value) ? $value : FALSE; }
ItemNote中的验证规则
public static $validationRules = array('note_date' => 'required|date',
'resolve_date' => 'nullable|date',
'notes' => 'required|string',
'cost' => 'nullable|numeric',
'calendar_item' => 'required|boolean',
'attachment_path' => 'nullable|string|max:200');
这是在 ItemNoteController 中从 Item 页面添加 ItemNote 时运行的操作
public function store(Item $item)
{
$this->validate(request(), ItemNote::$validationRules);
$item->addNote(new ItemNote(request(['item_note_category_id', 'note_date', 'resolve_date',
'notes', 'cost', 'calendar_item', 'attachment_path'])));
return back();
}
这里是Item模型中的addNote函数
public function addNote(ItemNote $note)
{
$this->item_note->save($note);
}
这是我在 addNote 中尝试过的不同方法,它们都无法运行 mutator。 create 语句列出了字段分配,但为简洁起见,我在此处删除了它们。
$this->notes->save($note);
$this->notes()->save($note);
$this->item_note->save($note);
$this->notes->create
$this->item_notes->create
$this->item_notes()->create
$this->item_note->create
$this->item_note()->create
$this->ItemNote->create
$this->ItemNote()->create
ItemNote::create
上述所有工作,虽然我认为 $this->item_notes->create 根本不应该工作,因为关系名称是 notes 但它没有抱怨,这让我认为它可能无法做到这一点代码并且它在控制器中的验证语句上失败。如何在验证之前运行变异器?或者有没有更好的方法在验证前清理数据?
我还尝试将 item_id 字段放入验证规则中,但这总是失败,因为在我通过关系创建对象之前未分配 item_id。我想要求它,但还没有弄清楚如何在请求中分配它。
感谢任何帮助。抱歉,帖子太长了。
【问题讨论】:
-
不知道怎么回事,但是这个语法是正确的:$this->notes()->save($note);
-
dd的结果是什么($item->addNote(new ItemNote(request(...))));
-
我把 dd($item->addNote(new ItemNote(request(['item_note_category_id', 'note_date', 'resolve_date', 'notes', 'cost', 'calendar_item', 'attachment_path ']))));在验证语句之前,我在 null 上调用了对成员函数 save() 的 FatalThrowableError 调用。也许我应该把它放在其他地方,在验证之后?
-
你修复了 addNote 方法吗? (见我的第一条评论)
-
如果我将 dd 行放在验证之后,它会运行并显示需要 calendar_item 字段的错误