Can you show the complete query. I don't quite understand why the main query is changed by using with() as that runs a completely seperate query
using paginate with eager loading on a relation with group
This is weird ;-) I have a search like this:
\App\Models\Books::with('Reads')->paginate(15)->withQueryString();
I have the Model Books with the relations "Reads" as this:
public function Reads() {
return $this->hasMany(Reads::class, 'book_id', 'id')
->groupBy('field');
}
The problem is that the groupBy is "affecting" the "with" eager loading with the pagination.
So, because of the "with", the relation is grouping by "field" on those elements appearing in that page ... so it's grouping on elements wherein the id of 15 elements (the 15 items in page).
And I want that relation to Reads to group ONLY in the relation book_id <> id
If I remove the "with", the relation is working perfectly. I see the query generated and it generates:
select * from Reads
where Reads.book_id = 10513
group by `field`
but when I use the "with" the where generated is:
select * from Reads
where Reads.book_id in ( 9743, 9773, 9823, 9851, 9877, 9879, 9880, 9881, 9910, 10055, 10057, 10058, 10131, 10489, 10513 )
group by `field`
Is there any solution ?
@skater I suggest use one or the other:
-
Joins and grouping or
-
Related data
And if you need a more detailed tutorial on aggregate usage see: https://www.mysqltutorial.org/mysql-group-by.aspx
Edit:
Related data is like:
Company A
--- List of their payables
Company B
--- List of their payables
etc
Aggregate / grouping is like:
$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
->select('dc_powners.ownerid', 'dc_powners.oname')
->selectRaw('count(dc_pets.petid) as countOfPets')
->groupby('dc_powners.ownerid')
->orderby('dc_powners.oname')
->get();
Results basically give:
ownerid, oname, countOfPets
Like:
5|Bob|3
4|Greg|9
2|Rob|1
Just examples
But in reports you also have section summaries and usually at the end some final totals. These summaries and final totals are separate queries.
Edit:
Seems you could just do something like:
Pseudocode
select the books that user_id 5 read // just example
Or are you wanting a list of who read what?
Bob
----read book 1
----read book 458
Dave
----read book 1
----read book 900
etc
Please or to participate in this conversation.