Framework: withCount() overrides Joins

Created on 11 May 2017  路  1Comment  路  Source: laravel/framework

  • Laravel Version: 5.4
  • PHP Version: 7.1
  • Database Driver & Version:

Description:

When chaining withCount() and join(), the withCount() overrides the entire join. This is not the case when chaining with() and join().

Steps To Reproduce:

$users = \App\User::withCount('followers')->join('user_settings', 'users.id', '=', 'user_settings.user_id')->get();
returns

{
id: 3,
name: "Rhea",
followers_count: 2
}...

this works however

$users = \App\User::with('followers')->join('user_settings', 'users.id', '=', 'user_settings.user_id')->get();
returns

{
id: 3,
name: "Rhea",
is_admin: 1,
verified: 1, 
followers: [
 {
  id: 138,
  user_id: 30,
  is_following: 1
 } ...
]
}...

I need to be able to order the resulting collection by a count of followers which is not possible via this method, which it seems it should be.

Most helpful comment

You can use something like:

User::select('*')->withCount('followers')->join(....)

This will instruct the builder to select all fields, by default only the base Model's fields are selected.

>All comments

You can use something like:

User::select('*')->withCount('followers')->join(....)

This will instruct the builder to select all fields, by default only the base Model's fields are selected.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JamborJan picture JamborJan  路  3Comments

gabriellimo picture gabriellimo  路  3Comments

felixsanz picture felixsanz  路  3Comments

YannPl picture YannPl  路  3Comments

jackmu95 picture jackmu95  路  3Comments