【问题标题】:Where clause in polymorphic relationship多态关系中的 where 子句
【发布时间】:2023-03-16 13:09:01
【问题描述】:

我有桌子

threads
- id
replies
- id
- repliable_id
- repliable_type

我想在 Thread 中添加另一列,即最近回复的 id。

Thread::where('id',1)->withRecentReply()->get()

以及以下查询范围

public function scopeWithRecentReply() {
    return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->whereHasMorph('repliable', ['App\Thread'], function ($q) {
                    $q->where('repliable_id', '=', 'threads.id');
                })->latest('created_at')
                ->take(1),
        ]);
}

我也试过

public function scopeWithRecentReply() {
    return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->where('repliable_id', '=', 'threads.id')
                ->latest('created_at')
                ->take(1),
        ]);
}

但在这两种情况下

recent_reply_id => null

如果我输入一个整数而不是 threads.id,它会起作用并且 recent_reply_id 不为空 例如

public function scopeWithRecentReply() {
    return $query->addSelect([
            'recent_reply_id' => Reply::select('id')
                ->whereHasMorph('repliable', ['App\Thread'], function ($q) {
                    $q->where('repliable_id', '=', 1);
                })->latest('created_at')
                ->take(1),
        ]);
}

我的问题是

有没有办法使用相应的 threads.id 获取 recent_reply_id

【问题讨论】:

    标签: laravel eloquent eloquent-relationship


    【解决方案1】:

    我建议使用appends 而不是query scopes,所以我们将在您的Thread 模型中添加

    protected $appends = ['recent_reply_id'];
    
    .....
    
    public function replies () {
        // you need to add here your relation with replies table
    }
    
    public function getRecentReplyIdAttribute () {
        return $this->replies()->latest('id')->first()->id;
    }
    

    现在无论您在哪里查询threads 表,您都可以像访问recent_reply_id 一样

    $thread = Thread::where('id',1)->withRecentReply()->get();
    
    $thread->recent_reply_id;
    

    【讨论】:

    • 实际上,我需要查询范围内的 id,因为我想继续构建查询,因为我要创建的查询比仅获取 id 复杂一点。
    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2017-01-20
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多