php - 在模型中附加来自另一个模型的数据(laravel 5.4)
问题描述
我想从我的数据库中的表中追加数据计数,但我遇到了关系问题。
我有 3 个模型
优惠券型号:
凭证系列型号:
每张优惠券将有许多连续剧
用户凭证模型:
当用户兑换凭证时,它将存储在 user_vouchers 表中。我还定义了所有模型的关系
在 Voucher.php 中,我想附加用户兑换的凭证的计数。
public function getVoucherRedeemedAttribute()
{
//query to append the voucher redeemed count for each voucher
}
我尝试了很多解决方案,但大多数时候我都遇到了错误。我最大的问题是因为要根据 user_vouches 表计算为每张优惠券兑换的优惠券,但每张优惠券都有很多我想算作同一张优惠券的 serial_id
我知道我对这个问题的解释很糟糕,但我需要一些帮助。希望可以有人帮帮我。
非常感谢你提前
解决方案
您可以使用以下方法将相关对象的数量添加到结果中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');
我从来没有真正一起使用过withCount
,hasManyThrough
但它应该可以工作;)
推荐阅读
- python - tkinter 模块中的语法错误。root = tk() TypeError: 'module' object is not callable
- html - Chrome 中的 Padding-inline-start 错误的 CSS 动画
- java - 将类类型存储为变量以在 java 的列表中识别下一个预期的对象类型
- google-bigquery - 比较 2 个表并使用具有最大值 Bigquery 的行更新最终表
- layout - 聚焦时门户行可编辑字段表现奇怪(FileMaker Pro 18)
- java - xml中的*替换表示任何字符串是什么
- wordpress - {多个项目} Woocommerce
- video-streaming - 如何对 H265/HEVC 的 RTP 数据(通过 UDP)中的碎片帧进行解包?
- javascript - 使用“import * as”和解构时的意外行为
- html - 如何在 Angular 8 中获取 Windows 用户名