我有一些模型定义了适当的belongsTo/hasMany关系,我想根据联接表的属性查询一个表。如果我在查询中定义联接,我可以做到这一点,但有没有什么我可以做的,这样我就不必每次查询模型的关系时都定义联接了?
例如。除非我定义了一个联接,否则以下操作不起作用:
FileAssociation::with('file')->where('files.file_type_version_id', $file->file_type_version_id)->get()
我认为你想要的是Eager Load Constraints,基本上你可以做这个
FileAssociation::with(array('file' => function($query)
{
$query->where('file_type_version_id',$file->file_type_version_id);
}))->get();
查看Eager Loading 上的文档
编辑
如果您现在使用Laravel 4.1,如果您只想在至少有一个"文件"的情况下返回FileAssociation
,则可以访问whereHas()
方法
FileAssociation::whereHas('file' => function($query)
{
$query->where('file_type_version_id',$file->file_type_version_id);
})->get();
查看有关查询关系的文档