php - Eloquent - 在嵌套函数中访问父值
问题描述
我正在尝试在嵌套函数中访问父值,即帖子日期。
在我的应用程序中,一个用户有很多帖子,每个帖子都与一个产品(教科书)相关联。每次有人查看产品页面时,都会在产品视图表中添加一个新行。
我想返回查看用户产品的累计次数。我已经能够获取所有用户的帖子,然后是相关产品,然后是该产品的所有视图的计数。
现在我想添加另一个 where() 条件以仅返回帖子创建后出现的视图。为此,我需要获取帖子日期,例如views->product->post,同时构造查询,如user->posts->product->views。
// getting all of the users available posts
$user = $request->user()->posts()->available()->with([
// with the textbook (product) associated with the post
'textbook' => function ($q) {
// get the count of textbook-page views
return $q->withCount([
// from the related table views
'views' => function ($q) {
// ===!!! Q !!!=== How do I access the posts (parent (grandparent?)) date, so that I only select the rows that have been viewed after the post was created ===!!!===
->where('date-viewed', '>=', 'posts.date');
},
]);
//some cleanup
}])->distinct()->get()->unique('isbn')->pluck('textbook.views_count')->sum();
如何在嵌套函数中倒退以访问帖子日期?
解决方案
看起来就像 Jonas 在评论中所说的那样,每个with()
关系都是一个新的查询,所以我最终hasManyThrough()
通过产品在帖子和视图之间创建了关系。
// getting all of the users available posts
$user = $request->user()->posts()->available()->withCount([
'views' => function ($q) {
// ===!!! A !!!=== Fixed ===!!!===
->whereRaw('`date-viewed` >= posts.date');
},
])->distinct()->get()->unique('isbn')->pluck('views_count')->sum();
推荐阅读
- angular - 无法在 Angular 中使用单击处理程序实现树视图
- reactjs - 有没有办法在其他组件中使用 withStateHandlers 中的函数?
- flutter - Flutter 无法加载资产
- powershell - powershell 输出 ad-computer foreach 的问题
- python - Python 在井字游戏中定义函数
- excel - 如何编写适用于任何工作簿的排序代码?
- machine-learning - 如何在python中绘制正确的超平面
- editor - ThebeLab的输入框(使用codemirror)如何设置样式?
- java - Java 11 (Zulu) 中的 DateTimeFormatter 不适用于 AM / PM 格式
- php - 如何打印脸书评论