【问题标题】:Error in laravel query builderlaravel 查询生成器中的错误
【发布时间】:2018-08-03 15:45:39
【问题描述】:

我的 Laravel 查询生成器返回 null:

    $country = DB::table('participate_company')

        ->join('company', 'company.company_id', '=', 'participate_company.company_id')
        ->join('country', 'country.country_id', '=', 'company', 'company.country_id')
        ->join('competition', 'competition.competition_id', '=', 'participate_company.competition_id')

        ->select('country.country_name', DB::raw('COUNT(company.country_id) as total'))
        ->groupBy('company.country_id')
        ->groupBy('country.country_name')
        ->get();

餐桌设计:

1.参与公司

competition_id (pk/fk)
company_id (pk/fk)

2.公司

company_id (pk)
公司名称
country_id (fk)

3.国家

country_id (pk)
国名

4.比赛

competition_id (pk)
比赛年

我想根据比赛年份产生计数不同国家的结果。例如比赛年份 = 2012,country_name = England,count(total) = 20。但我当前的查询结果为 null。

SQLFiddle:http://sqlfiddle.com/#!9/a2092f/1

【问题讨论】:

  • 请将您选择的数据放在fiddle 上,我很乐意查看。谢谢...
  • @hd1 我已经编辑了我的帖子并添加了 sql fiddle ...请看一下谢谢
  • 您希望从该查询中得到什么结果?我能够得到“英格兰”

标签: php mysql laravel-5 laravel-query-builder


【解决方案1】:

我建议使用Laravel ORM RelationshipEager Loading 来解决这个问题。 在公司模型中,我们将定义country()method:

public function country() {
       return $this->belongsTo(Country::class, 'country_id', 'id');
}

在竞争模型中,定义方法

public function company() {
       return $this->belongsToMany(Company::class);
}

所以在控制器中你可以调用groupBy

Competition::with('company:id,country_id')->get()->groupBy('year');

我们将在yearsrelations 中的每个company 中捕获country_id。 我只是测试了一个简单的例子,之后,我们将循环这个集合并计算它们。

希望这有用。

P/s。作为模型使用,我的表名称:companiescountriescompetitionscompany_competition

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 2018-08-03
    • 2017-06-24
    • 1970-01-01
    • 2016-12-31
    • 2016-12-08
    • 2016-04-25
    • 2017-03-01
    • 2015-12-13
    相关资源
    最近更新 更多