dongying3830 2014-08-25 01:23
浏览 36

计算Laravel中的远距离关系(渴望加载?)

I'm having issues getting a proper count total with my Laravel model.

Model Structure

  • User
  • Item
  • ItemLike

A user can have multiple Items, and each of these Items can have multiple ItemLikes (when a user 'likes' the item).

I can easily get the individual ItemLike counts when using an Item model:

return $this->itemLikes()->count();

But I can't figure out how to get the total # of ItemLike's a User has across all the Item's he owns.

EXAMPLE

User A has 3 Items. Each Item has 5 ItemLike's, for a grand total of 15.

I tried using eager loading on the User model like this:

return $this->items()->with('itemlikes')->get()->count();

But that returns 3 (the # of Items)

These are the queries it ran, which appears like the second query is the one I want, yet every way I try it I still get 3 instead of 15

select * from `items` where `items`.`user_id` = '1000'
select * from `item_likes` where `item_likes`.`item_id` in ('1000', '1001', '1002')
  • 写回答

3条回答 默认 最新

  • dpg76975 2014-08-25 01:38
    关注

    Isn't it just a case of creating a method that would return the number of items for the model. e.g.:

    #UserModel
    public function nbLikes()
    {
        $nbLikes = 0;
        foreach($this->items() as $item) {
            $nbLikes += $item->itemLikes()->count();
        }
    
        return $nbLikes;
    }
    

    And then User::nbLikes() should return the piece of data you are looking for?

    评论

报告相同问题?