Laravel 4:仅获取具有相关模型的模型 [英] Laravel 4: fetching only models that have related models

查看:70
本文介绍了Laravel 4:仅获取具有相关模型的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在模型具有特定的相关模型时检索模型.

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();

我收到以下错误:

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 }}

当那个jobApplication没有工作时,显然会收到以下错误:

obviously gets the following error when that jobApplication has no job:

Trying to get property of non-object

推荐答案

发生这种情况的原因是,当数据库上具有1->n关系时,n部分可能具有多个与之相关的注册.但是,反过来是不一样的. post可能有n条评论,但一条评论belongs to中只有一个帖子.因此,方法has('model')不适用于这种情况.

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.

希望有帮助!

这篇关于Laravel 4:仅获取具有相关模型的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆