I want to only retrieve a model(s) when they have a specific related model present e.g.
我想仅在具有特定相关模型的模型时才检索模型,例如
$posts = Post::has('comment')->get();
that works fine although the opposite does not:
虽然相反,但工作正常:
$comments = Comment::has('post')->get();
I get the following error:
我收到以下错误:
Has method invalid on "belongsTo" relations.
Basically the reason i want to do this is that in exceptional circumstances there are cases that when i call a related model in a view, that model may not have a related model present (even when it should) sometimes due to bad data in the database etc....
基本上我想要这样做的原因是,在特殊情况下,有些情况下,当我在视图中调用相关模型时,该模型可能没有相关模型存在(即使它应该)有时由于数据库中的错误数据等等....
{{ $jobApplication->job->title }}
obviously gets the following error when that jobApplication has no job:
当jobApplication没有工作时,显然会出现以下错误:
Trying to get property of non-object
1 个解决方案
#1
0
That happens cause, when you have a 1->n
relation on your database, the n
part may has more than one register related to it. But, ain't the same the other way around. A post
may have n
comments, but a comment belongs to
only one post. So, the method has('model')
doesn't apply to this cases.
这种情况会导致,当您的数据库中存在1-> n关系时,n部分可能有多个与之相关的寄存器。但是,反过来说是不一样的。帖子可能有n个评论,但评论只属于一个帖子。因此,该方法具有('model')不适用于这种情况。
The solution for you problem, though, would be veirify if the variable is set. Try to do this on the controller.
但是,如果设置了变量,那么问题的解决方案就会产生问题。尝试在控制器上执行此操作。
Hope it help!
希望它有所帮助!
#1
0
That happens cause, when you have a 1->n
relation on your database, the n
part may has more than one register related to it. But, ain't the same the other way around. A post
may have n
comments, but a comment belongs to
only one post. So, the method has('model')
doesn't apply to this cases.
这种情况会导致,当您的数据库中存在1-> n关系时,n部分可能有多个与之相关的寄存器。但是,反过来说是不一样的。帖子可能有n个评论,但评论只属于一个帖子。因此,该方法具有('model')不适用于这种情况。
The solution for you problem, though, would be veirify if the variable is set. Try to do this on the controller.
但是,如果设置了变量,那么问题的解决方案就会产生问题。尝试在控制器上执行此操作。
Hope it help!
希望它有所帮助!