Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

withCount bug when using custom select #24797

Closed
mnabialek opened this issue Jul 10, 2018 · 4 comments
Closed

withCount bug when using custom select #24797

mnabialek opened this issue Jul 10, 2018 · 4 comments

Comments

@mnabialek
Copy link
Contributor

  • Laravel Version: v5.6.26
  • PHP Version: 7.2.5
  • Database Driver & Version: MySQL 8.0.11

Description:

Using withCount together with conditions and custom select causes running invalid queries.

Steps To Reproduce:

When having relationship defined like this:

public function userImages()
{
    return $this->hasMany(Image::class)->where('type', 'user');
}

When running code like this:

$query = Model::where('status', 'online')->select(['*'])->withCount('userImages');

or

$query = Model::where('status', 'online')->withCount('userImages');

SQL looks like this:

select `models`.*, (select count(*) from `images` where `models`.`id` = `images`.`model_id` and `type` = ?) as `user_images_count` from `models` where `status` = ?

and bindings look like this:

array:2 [
  0 => "user"
  1 => "online"
]

so everything is as expected.

But running code like this

$query = Model::where('status', 'online')->withCount('userImages')->select(['*']);

SQL looks like this:

select * from `models` where `status` = ?

and bindings looks like this:

array:2 [
  0 => "user"
  1 => "online"
]

The are at least 3 problems here:

  1. $result->user_images_count will result invalid value
  2. bindings are wrong so invalid data will be taken from database
  3. there is no exception thrown anywhere (or any information about such behavior in documentation) so without debugging query it's really hard to detect that query is completely invalid
@Harry-Torry
Copy link

With how select() sets the columns ($this->columns = is_array($columns) ? $columns : func_get_args();), it wipes the columns that get set by the withCount() call. You're explicitly stating you want XYZ field and then removing that field.

Try calling the select() before the withCount()!

@Harry-Torry
Copy link

Here's another one about the same "issue" - #19388.

@mnabialek
Copy link
Contributor Author

mnabialek commented Jul 11, 2018

@Harry-Torry I'm total aware that changing order fix the issue (I showed this in the issue). I also saw implementation, but it's quite risky when it works like this and there is no additional information about this in documentation.

@Harry-Torry
Copy link

Submit a PR to the docs 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants