首页 > 解决方案 > 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();

如何在嵌套函数中倒退以访问帖子日期?

标签: phplaravellaravel-5eloquent

解决方案


看起来就像 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();

推荐阅读