简体   繁体   English

我能在哪里雄辩地提到模型关系?

[英]Eloquent can I refer to model relationship in where?

I have models with appropriate belongsTo/hasMany relationships defined, and I want to query one table based on properties of a joined table. 我有定义了适当的belongsTo / hasMany关系的模型,并且我想根据联接表的属性查询一个表。 I can do it if I define the join in my query, but is there something I can do so that I don't have to define the join everytime I want to query a model on it's relation? 如果我在查询中定义了联接,就可以这样做,但是有什么我可以做的,这样我就不必每次都要查询有关其关系的模型时都定义联接了吗?

Forinstance. 例如。 the following does not work, unless I define a join: 除非定义了联接,否则以下命令将不起作用:

FileAssociation::with('file')->where('files.file_type_version_id', $file->file_type_version_id)->get()

I think what you want is Eager Load Constraints basically you can do this 我认为您想要的是基本的负载约束,基本上您可以做到这一点

FileAssociation::with(array('file' => function($query)
{
  $query->where('file_type_version_id',$file->file_type_version_id);
}))->get(); 

Check out the docs on Eager Loading 查看有关急切加载的文档

Edit 编辑

If you are using Laravel 4.1 now you have access to the whereHas() method if you want to return the FileAssociation only if there is at least one "file" 如果您现在使用的是Laravel 4.1, FileAssociation仅在至少有一个“文件”的情况下要返回FileAssociation则可以访问whereHas()方法。

FileAssociation::whereHas('file' => function($query)
{
  $query->where('file_type_version_id',$file->file_type_version_id);
})->get(); 

Check out the docs on Quering Relations 查看有关查询关系的文档

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

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