简体   繁体   中英

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 :

$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.

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.

How can I convert this query to proper 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:

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

Basically you can use "with" method to get 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 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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