Fahad Khan
Fahad Khan

Reputation: 1635

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.

Upvotes: 2

Views: 1665

Answers (2)

kamlesh.bar
kamlesh.bar

Reputation: 1804

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();

Upvotes: 1

jacquestvanzuydam
jacquestvanzuydam

Reputation: 86

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

Upvotes: 2

Related Questions