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

hasMany relationship, count/sum/max/min fields #7

Open
coryrose1 opened this issue Nov 19, 2019 · 1 comment
Open

hasMany relationship, count/sum/max/min fields #7

coryrose1 opened this issue Nov 19, 2019 · 1 comment
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@coryrose1
Copy link
Owner

coryrose1 commented Nov 19, 2019

Currently only belongsTo and hasOne work out of the box.

The query builder can be modified to support hasMany relationships and return a count, sum, min, or max column/field.

The challenge is building this into the existing query builder.

Here is an example of how the end query might be built:

$query->select('users.id', 'name', 'addresses.city', DB::raw('COUNT(posts.id) as posts_count'))
            ->leftJoin('addresses', 'users.id', '=', 'addresses.user_id')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->groupBy('users.id', 'addresses.city')
            ->paginate(15);

Effectively, the DB::raw call must be built into the select, and the groupBy() clause must be added.

One unfortunate thing I ran into is MySQL is in STRICT mode by default and thus every other "left join" relationship field must be included into the groupBy clause.

We might allow someone to specify these fields like so:

 public $fields = [
        [
            'title' => 'ID',
            'name' => 'id',
            'header_class' => '',
            'cell_class' => '',
            'sortable' => true,
            'searchable' => true,
        ],
        ...
        [
            'title' => 'Post Count',
            'name' => 'posts.count',
            'header_class' => '',
            'cell_class' => '',
            'sortable' => true,
            'searchable' => true,
        ],
    ];

where .count, .sum, .max, .min etc are reserved keywords that the query builder will parse and understand how to build the query.

@coryrose1 coryrose1 added enhancement New feature or request help wanted Extra attention is needed labels Nov 19, 2019
@kdion4891
Copy link

kdion4891 commented Jan 28, 2020

For count you can just call withCount on the model instance. Then in the table you can pass relationshipname_count. You can even add a new withCount method that can be used in component classes...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants