Change raw query join into laravel Eloquent

若如初见. 提交于 2019-12-22 11:29:32

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/29913238/change-raw-query-join-into-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!