2

Good day all, I am trying to count all records in a table but only if the table does not contain data in a specific column (deleted_at). It is a join table the table names are companies and employees. I am currently counting the records with a DB::raw but it should only count it if the deleted_at column is null. Please understand that i am a beginner.

public function index() { $user = Auth::user()->id; $companies = DB::table('companies AS c') ->select([ 'c.id', 'c.logo', 'c.company_name', 'c.created_at', 'c.sector', 'c.deleted_at', DB::raw('COUNT(e.id) AS employee_count') ]) ->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' ) ->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id') ->where('cu.user_id', '=', $user) ->where('c.deleted_at', '=', null) ->groupBy('c.id') ->get(); return view('account.companies.index') ->with('companies', $companies); } 

2 Answers 2

4

If you are using Mysql then you could use conditional aggregation

$companies = DB::table('companies AS c') ->select([ 'c.id', 'c.logo', 'c.company_name', 'c.created_at', 'c.sector', 'c.deleted_at', DB::raw('SUM(c.deleted_at IS NULL) AS employee_count') ]) ->leftJoin('employees AS e', 'e.company_id', '=', 'c.id' ) ->leftJoin('company_user AS cu', 'cu.company_id', '=', 'c.id') ->where('cu.user_id', '=', $user) ->groupBy('c.id') ->get(); 

In mysql when an expression is used inside sum(a= b) it will result as a boolean 0/1 so you can get your conditional count using above

Or you could use whereNull() method in your query

->whereNull('c.deleted_at') 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, both methods works. just changed from c.deleted_at to e.deleted_at. Have a wonderfull day :)
0

Use this code:

$employeeCount = DB::table('employees') ->select('companies.name', DB::raw('count(employees.id) as employee_count')) ->join('companies', 'employees.company','=','companies.id') ->groupBy('companies.id') ->get(); 

1 Comment

Your answer does not address the user's question, and contains no explanation. As well, the question is 3 years old and has an accepted answer already.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.