简体   繁体   English

Laravel 4:仅获取具有相关模型的模型

[英]Laravel 4: fetching only models that have related models

I want to only retrieve a model(s) when they have a specific related model present eg 我只想在有特定相关模型的情况下检索模型,例如

$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

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. 发生这种情况的原因是,当数据库上具有1->n关系时, n部分可能多个与之相关的寄存器。 But, ain't the same the other way around. 但是,反过来是不一样的。 A post may have n comments, but a comment belongs to only one post. 一个post可能有n评论,但一条评论仅belongs to一个帖子。 So, the method has('model') doesn't apply to this cases. 因此,方法has('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! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM