我有两个型号:
$modelMain = "SearchPages"; //table_name : search_pages
$modelSites = "Site"; // table_name : sites
我最初有一个以下查询只从一个模型 $modelMain
获取计数:
$records = $modelMain::
select(DB::raw("COUNT(DISTINCT {$columnRecordedOn}) as records_count"))
->groupBy($columnRecordedOn, $columnSiteId)
->get();
现在,我需要加入第二个模型 $modelSites
whoese表名是 sites
,以检查 sites
中的状态列(如果为1) .
我将查询修改为:
$records = $modelMain::
select(DB::raw("COUNT(DISTINCT {$columnRecordedOn}) as records_count"))
->join('sites','search_pages.site_id','=','sites.site_id') //added this
->where('sites.status','=','1') // and this
->groupBy($columnRecordedOn, $columnSiteId)
->get();
所有工作正常但你可以看到我直接在 join()
和 where()
中使用表名 sites
而是我必须使用模型名称我相信 .
如何将此查询转换为正确的Laravel Eloquent?
谢谢你的帮助 .
2 回答
基本上你可以使用“with”方法来获得相关的模型
网站模型
SearchPage模型
$ records = SearchPage :: with('site') - > get();
根据您的需要
您是否看过使用Eloquent中的关系,您应该在两个模型中声明关系,例如:
有关Eloquent和关系的更多信息,请参阅此参考:http://laravel.com/docs/4.2/eloquent#relationships