【问题标题】:Last record in HasManyThrough PivotHasManyThrough Pivot 中的最后记录
【发布时间】:2021-06-07 19:23:57
【问题描述】:

我正在尝试获取 HasManyThrough 中数据透视表中的最后一条记录。 有4张桌子: 代表 地点 状态 委托位置状态

在 DelegateLocationStatus 表中,每个 Delegate 都有重复的记录,显示每个状态的进度。我希望仅获取具有特定 StatusID 作为其在 DLS 表中的最后一条记录的 Delegates 的最后一条记录。

return $this->hasManyThrough(
                Delegate::class,
                DelegateLocationStatus::class,
                'fldCID', // Foreign key on the environments table...
                'ID', // Foreign key on the deployments table...
                'ID', // Local key on the projects table...
                'fldUID' // Local key on the environments table...
        );

我试过像这样添加 where 子句

return $this->hasManyThrough(
                Delegate::class,
                DelegateLocationStatus::class,
                'fldCID', // Foreign key on the environments table...
                'ID', // Foreign key on the deployments table...
                'ID', // Local key on the projects table...
                'fldUID' // Local key on the environments table...
        )->where('nm_table_user', function($q) {
            $q->select('fldSTATUSID')
            ->from('nm_tbl_cate_puser_user')
            ->where('fldSTATUSID', '=', 6)
            ->orderBy('ID', 'DESC')
            ->limit(1);
        });

但我真的不知道如何只针对 DLS 表中 StatusID 为 6 的最后一条记录。

我希望这是有道理的。 谢谢。

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    您可以使用 latest('created_at') 或 latest('updated_at') 选择最后添加或更新的记录。

    return $this->hasManyThrough(
                    Delegate::class,
                    DelegateLocationStatus::class,
                    'fldCID', // Foreign key on the environments table...
                    'ID', // Foreign key on the deployments table...
                    'ID', // Local key on the projects table...
                    'fldUID' // Local key on the environments table...
            )->where('nm_table_user', function($q) {
                $q->select('fldSTATUSID')
                ->from('nm_tbl_cate_puser_user')
                ->where('fldSTATUSID', '=', 6)
                ->latest('created_at')
                ->orderBy('ID', 'DESC')
                ->limit(1);
            });
    

    【讨论】:

    • 感谢您的回复。当它应该带回 16 个结果时,它仍然带回 17 个结果。某人的倒数第二个结果是 StatusID 为 6,因此应该忽略它。
    猜你喜欢
    • 2015-12-14
    • 2019-02-12
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多