[英]Change raw query join into laravel Eloquent
I have two models: 我有两个模型:
$modelMain = "SearchPages"; //table_name : search_pages
$modelSites = "Site"; // table_name : sites
I initially had a below query for getting count from only one model $modelMain
: 我最初有一个下面的查询,仅从一个模型
$modelMain
获取计数:
$records = $modelMain::
select(DB::raw("COUNT(DISTINCT {$columnRecordedOn}) as records_count"))
->groupBy($columnRecordedOn, $columnSiteId)
->get();
Now, I need to join it with 2nd model $modelSites
whoese table name is sites
in order to check status column in sites
if its 1. 现在,我需要用第二模型加入吧
$modelSites
whoese表名是sites
为了在检查状态栏sites
如果它的1。
I modified the query to: 我将查询修改为:
$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();
All working fine but as you can see I am using table name sites
directly in join()
and in where()
instead I must use model name I believe. 一切正常,但是如您所见,我直接在
join()
和where()
使用表名称sites
,而必须使用我相信的模型名称。
How can I convert this query to proper Laravel Eloquent? 如何将该查询转换为适当的Laravel Eloquent?
Thanks for any help. 谢谢你的帮助。
Have you looked at using the relationships in Eloquent, you should declare the relationship in your two models, something like: 您是否曾在Eloquent中使用过关系,应该在两个模型中声明该关系,例如:
class SearchPages extends Eloquent {
public function sites()
{
return $this->hasMany('sites');
}
}
For more on Eloquent and relationships look at this reference: http://laravel.com/docs/4.2/eloquent#relationships 有关Eloquent和关系的更多信息,请参见以下参考资料: http : //laravel.com/docs/4.2/eloquent#relationships
Basically you can use "with" method to get related model 基本上,您可以使用“ with”方法来获取相关模型
Site Model 网站模型
class Site extends Eloquent {
public function searchpages()
{
return $this->hasMany('SearchPage','site_id','site_id');
}
}
SearchPage Model SearchPage模型
class SearchPage extends Eloquent {
public function site()
{
return $this->belongTo('Site','site_id','site_id');
}
}
$records = SearchPage::with('site')->get(); $ records = SearchPage :: with('site')-> get();
as per your need 根据您的需要
$records = SearchPage::
select(DB::raw("COUNT(DISTINCT {$columnRecordedOn}) as records_count"))
->whereHas('site' => function($q){
$q->where('status','1');
})
->groupBy($columnRecordedOn, $columnSiteId)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.