mercredi 26 avril 2017

Laravel 5: How to count number of items in a relashionship

I have the following table:

  • Users
    • id
    • name
  • Books
    • id
    • name
    • user_id
    • purchased (bool)

How can I use Laravel to efficiently get all the users and the number of books each user has purchased.

The closest I have got is the following:

 $users = User::
        ->with(['books' => function ($query) {
            $query->select(DB::raw('count(*) as number_of_purchased_books')
                ->where('purchased', '=', true);
        }])
        ->get();
 dump($users->toArray())

But the above doesn't seem to return anything for the number_of_purchased_books property.

What am I doing wrong?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2oMq0zW
via IFTTT

Aucun commentaire:

Enregistrer un commentaire