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

[5.3] Limit in eager loading doesn't feel right #15585

Closed
shadoWalker89 opened this issue Sep 24, 2016 · 1 comment
Closed

[5.3] Limit in eager loading doesn't feel right #15585

shadoWalker89 opened this issue Sep 24, 2016 · 1 comment

Comments

@shadoWalker89
Copy link
Contributor

shadoWalker89 commented Sep 24, 2016

  • Laravel Version: 5.3.6
  • PHP Version:5.6.15
  • Database Driver & Version:Mysql 5.6.31

I have this eloquent Query

$themes = DataTheme::withCount('dataSets')
->with([
    'dataSets' => function ($query)
    {
        $query->limit(5);
    }
])
->orderBy('data_sets_count', 'desc')
->get();

The dataSets on the DataTheme model is belongsToMany()

This is how i understand the eloquent query

Select all data themes
Select the total count of data sets related to each data theme
For each data theme select only 5 data sets

And this is the generated sql

SELECT 
  *,
  (SELECT 
    COUNT(*) 
  FROM
    `data_sets` 
    INNER JOIN `data_set_data_theme` 
      ON `data_sets`.`id` = `data_set_data_theme`.`data_set_id` 
  WHERE `data_set_data_theme`.`data_theme_id` = `data_themes`.`id`) AS `data_sets_count` 
FROM
  `data_themes` 
ORDER BY `data_sets_count` DESC;

SELECT 
  `data_sets`.*,
  `data_set_data_theme`.`data_theme_id` AS `pivot_data_theme_id`,
  `data_set_data_theme`.`data_set_id` AS `pivot_data_set_id` 
FROM
  `data_sets` 
  INNER JOIN `data_set_data_theme` 
    ON `data_sets`.`id` = `data_set_data_theme`.`data_set_id` 
WHERE `data_set_data_theme`.`data_theme_id` IN ('1', '2', '3', '4') 
LIMIT 5 

As you can see the Explenation that i provided doesn't match the sql code.

The sql is just selecting 5 datasets and not 5 datasets for each data theme

Is my explenation of the Eloquent query correct ?

@GrahamCampbell
Copy link
Member

Looks correct. It's just not possible to limit in the way that you want. This has come up before I think.

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