首页 文章

将原始查询连接更改为laravel Eloquent

提问于
浏览
2

我有两个型号:

$modelMain = "SearchPages"; //table_name : search_pages
$modelSites = "Site"; // table_name : sites

我最初有一个以下查询只从一个模型 $modelMain 获取计数:

$records = $modelMain::
        select(DB::raw("COUNT(DISTINCT {$columnRecordedOn}) as records_count"))
        ->groupBy($columnRecordedOn, $columnSiteId)
        ->get();

现在,我需要加入第二个模型 $modelSites whoese表名是 sites ,以检查 sites 中的状态列(如果为1) .

我将查询修改为:

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

所有工作正常但你可以看到我直接在 join()where() 中使用表名 sites 而是我必须使用模型名称我相信 .

如何将此查询转换为正确的Laravel Eloquent?

谢谢你的帮助 .

2 回答

  • 1

    基本上你可以使用“with”方法来获得相关的模型

    网站模型

    class Site extends Eloquent {
    
        public function searchpages()
        {
        return $this->hasMany('SearchPage','site_id','site_id');
        }
    
    }
    

    SearchPage模型

    class SearchPage extends Eloquent {
    
        public function site()
        {
        return $this->belongTo('Site','site_id','site_id');
        }
    
    }
    

    $ records = SearchPage :: with('site') - > get();

    根据您的需要

    $records = SearchPage::
           select(DB::raw("COUNT(DISTINCT {$columnRecordedOn}) as records_count"))
        ->whereHas('site' => function($q){
                                            $q->where('status','1');
                                        })
        ->groupBy($columnRecordedOn, $columnSiteId)
        ->get();
    
  • 2

    您是否看过使用Eloquent中的关系,您应该在两个模型中声明关系,例如:

    class SearchPages extends Eloquent {
    
        public function sites()
        {
        return $this->hasMany('sites');
        }
    
    }
    

    有关Eloquent和关系的更多信息,请参阅此参考:http://laravel.com/docs/4.2/eloquent#relationships

相关问题