Laravel让建设者而不是关系 [英] Laravel getting builder instead of relation
问题描述
我正在尝试在保存模型之前对其进行验证.显然,如果模型无效,则不应将其保存到数据库.验证失败时,它将引发异常,并且不会继续保存.这在下面起作用:
I am trying to validate a model before saving it. Obviously if the model isn't valid, it shouldn't be saved to the database. When validation fails, it throws an exception and doesn't continue to save. This below works:
$question = new Question([...]);
$question->validate();
$question->save();
answers()
hasMany关系有问题.根据此答案,我应该能够在关系对象上调用add()
:
I have a problem with the answers()
hasMany relationship. According to this answer I should be able to call add()
on the relation object:
$question = new Question([...]);
$question->answers()->add(new Answer([...]));
$question->validate();
$question->save();
以上操作失败:
Call to undefined method Illuminate\Database\Query\Builder::add()
我以为answer()函数将返回HasMany关系对象,但是看起来我正在获得一个生成器.为什么?
I thought the answers() function would return a HasMany relationship object, but it looks like I'm getting a builder instead. Why?
推荐答案
answers()
确实返回一个HasMany对象.但是,由于HasMany
对象上没有add
方法,因此Laravel求助于PHP的__call
魔术方法.
answers()
does return a HasMany object. However, because there is no add
method on a HasMany
object, Laravel resorts to PHP's __call
magic method.
public function __call($method, $parameters)
{
$result = call_user_func_array([$this->query, $method], $parameters);
if ($result === $this->query) {
return $this;
}
return $result;
}
__call
方法获取查询实例,并尝试在其上调用add
方法.但是,查询生成器上没有add
方法,这就是为什么收到该消息的原因.
The __call
method gets the query instance and tries to call the add
method on it. There is no add
method on the query builder though, which is why you are getting that message.
最后,add
方法是Laravel的Eloquent Collection的一部分,而不是HasMany的一部分.为了获得Collection类,您需要删除括号(如链接中提供的答案所示),然后执行以下操作:
Finally, the add
method is part of Laravel's Eloquent Collection, not a part of HasMany. In order to get the Collection class, you need to drop the parenthesis (as shown in the answer provided in your link) and do this instead:
$question->answers->add(new Answer([...]));
这篇关于Laravel让建设者而不是关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!