首页 > 解决方案 > 在模型中附加来自另一个模型的数据(laravel 5.4)

问题描述

我想从我的数据库中的表中追加数据计数,但我遇到了关系问题。

我有 3 个模型

优惠券型号

代金券表

凭证系列型号:

凭证序列表

每张优惠券将有许多连续剧

用户凭证模型:

user_vouchers 表

当用户兑换凭证时,它将存储在 user_vouchers 表中。我还定义了所有模型的关系

在 Voucher.php 中,我想附加用户兑换的凭证的计数。

 public function  getVoucherRedeemedAttribute()
{         
   //query to append the voucher redeemed count for each voucher
}

我尝试了很多解决方案,但大多数时候我都遇到了错误。我最大的问题是因为要根据 user_vouches 表计算为每张优惠券兑换的优惠券,但每张优惠券都有很多我想算作同一张优惠券的 serial_id

我知道我对这个问题的解释很糟糕,但我需要一些帮助。希望可以有人帮帮我。

非常感谢你提前

标签: phplaravel-5

解决方案


您可以使用以下方法将相关对象的数量添加到结果中withCount

如果你想计算一个关系的结果数而不实际加载它们,你可以使用 withCount 方法,它会在你的结果模型上放置一个 {relation}_count 列。例如:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

来源:https ://laravel.com/docs/5.8/eloquent-relationships#counting-related-models

如果我正确理解您的问题,您希望将计数更深一层(优惠券数量而不是优惠券系列数量)。您可能可以使用hasManyThrough关系:

“has-many-through”关系为通过中间关系访问远距离关系提供了便捷的捷径。例如,一个 Country 模型可能通过一个中间 User 模型有许多 Post 模型。在此示例中,您可以轻松收集给定国家/地区的所有博客文章。

来源:https ://laravel.com/docs/5.8/eloquent-relationships#has-many-through

结合起来,它看起来像这样:

class User {
    //...
    public function vouchers()
    {
        return $this->hasManyThrough(App\Voucher::class, App\VoucherSerial::class);
    }
}

// Controller
$user->withCount('vouchers');

我从来没有真正一起使用过withCounthasManyThrough但它应该可以工作;)


推荐阅读