0

My Laravel query builder 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 design:

1. Participate_company

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

2. company

company_id (pk)
company_name
country_id (fk)

3. country

country_id (pk)
country_name

4. competition

competition_id (pk)
competition_year

I want to produce result of count distinct country based on competition year. For example competition year = 2012, country_name = England, count(total) = 20. But my current query produce null.

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

3
  • Please put a selection of your data on a fiddle and I'd be happy to take a look at it. Thank you... Commented Jul 9, 2018 at 10:12
  • @hd1 I had edit my post and add sql fiddle ... please take a look on it thank you Commented Jul 10, 2018 at 3:08
  • what results are you expecting from that query? I was able to get "England" Commented Jul 10, 2018 at 4:58

1 Answer 1

1

I suggest using Laravel ORM Relationship and Eager Loading to solve this problem. In Company model, we would define country()method:

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

In Competition model, define method

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

So in controller you can call groupBy :

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

We will catch country_id in each company which is in relations of years. I just tested a simple example, after that, we will loop over this collection and count them .

Simple example

Hope this's usefull.

P/s. As using by models, my table's names: companies, countries, competitions, company_competition

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.