laravel 查询生成器出错
Error in laravel query builder
我的 Laravel 查询生成器 return 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();
Table设计:
1. Participate_company
competition_id (pk/fk)
company_id (pk/fk)
2。公司
company_id (pk)
company_name
country_id (fk)
3。国家
country_id (pk)
country_name
4。比赛
competition_id (pk)
competition_year
我想根据比赛年份生成不同国家/地区的计数结果。例如比赛年 = 2012,country_name = 英格兰,计数(总计)= 20。但我当前的查询产生空值。
SQLFiddle : http://sqlfiddle.com/#!9/a2092f/1
我建议使用Laravel ORM Relationship and Eager Loading来解决这个问题。
在 Company 模型中,我们将定义 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');
我们将在 years
的 relations
中的每个 company
中捕获 country_id
。
我只是测试了一个简单的例子,之后我们将遍历这个集合并计算它们。
希望这对你有用。
P/s。作为模特使用,我的 table 的名字:companies
、countries
、competitions
、company_competition
我的 Laravel 查询生成器 return 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();
Table设计:
1. Participate_company
competition_id (pk/fk)
company_id (pk/fk)
2。公司
company_id (pk)
company_name
country_id (fk)
3。国家
country_id (pk)
country_name
4。比赛
competition_id (pk)
competition_year
我想根据比赛年份生成不同国家/地区的计数结果。例如比赛年 = 2012,country_name = 英格兰,计数(总计)= 20。但我当前的查询产生空值。
SQLFiddle : http://sqlfiddle.com/#!9/a2092f/1
我建议使用Laravel ORM Relationship and Eager Loading来解决这个问题。
在 Company 模型中,我们将定义 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');
我们将在 years
的 relations
中的每个 company
中捕获 country_id
。
我只是测试了一个简单的例子,之后我们将遍历这个集合并计算它们。
希望这对你有用。
P/s。作为模特使用,我的 table 的名字:companies
、countries
、competitions
、company_competition