Laravel 4: fetching only models that have related models

半城伤御伤魂 提交于 2019-12-11 06:26:15

问题


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:

Trying to get property of non-object

回答1:


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.

The solution for you problem, though, would be veirify if the variable is set. Try to do this on the controller.

Hope it help!



来源:https://stackoverflow.com/questions/21281465/laravel-4-fetching-only-models-that-have-related-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!