i have 2 models:
$modelmain = "searchpages"; //table_name : search_pages $modelsites = "site"; // table_name : sites
i had below query getting count 1 model $modelmain
:
$records = $modelmain:: select(db::raw("count(distinct {$columnrecordedon}) records_count")) ->groupby($columnrecordedon, $columnsiteid) ->get();
now, need join 2nd model $modelsites
whoese table name sites
in order check status column in sites
if 1.
i modified query to:
$records = $modelmain:: select(db::raw("count(distinct {$columnrecordedon}) records_count")) ->join('sites','search_pages.site_id','=','sites.site_id') //added ->where('sites.status','=','1') // , ->groupby($columnrecordedon, $columnsiteid) ->get();
all working fine can see using table name sites
directly in join()
, in where()
instead must use model name believe.
how can convert query proper laravel eloquent?
thanks help.
basically can use "with" method related model
site model
class site extends eloquent { public function searchpages() { return $this->hasmany('searchpage','site_id','site_id'); } }
searchpage model
class searchpage extends eloquent { public function site() { return $this->belongto('site','site_id','site_id'); } }
$records = searchpage::with('site')->get();
as per need
$records = searchpage:: select(db::raw("count(distinct {$columnrecordedon}) records_count")) ->wherehas('site' => function($q){ $q->where('status','1'); }) ->groupby($columnrecordedon, $columnsiteid) ->get();