【问题标题】:Eloquent query that queries based on a relationship with a relationship雄辩的查询,基于与关系的关系进行查询
【发布时间】:2018-06-12 14:12:40
【问题描述】:

试图在标题中描述我的问题很困难。我的意思是这个。我有 3 张桌子。工作,日记,文件。 每个日记条目与 Job 都有一个 belongsTo 关系。每个 Document 和 Diary 都有一个 belongsTo 关系。

如何查询 Documents 以便返回属于单个作业的所有文档。

Document->diary_id 引用 Diary->id - Diary->job_number_id 引用 Job->id

这两种个人关系都已建立并有效。

我尝试了不同的查询,但没有成功。

任何帮助表示赞赏。 问候 芬奇70

【问题讨论】:

    标签: laravel-5 eloquent


    【解决方案1】:

    使用HasManyThrough 关系:

    public function documents() {
        return $this->hasManyThrough(Document::class, Diary::class, 'job_number_id');
    }
    
    $documents = $job->documents()->paginate(15);
    

    【讨论】:

    • 谢谢。我目前不在我的 Mac 上,但会在早上尝试并反馈。不过看起来不错。
    • 工作如梦。谢谢。
    【解决方案2】:

    我继续研究并尝试了不同的 eloquent 查询,并找到了一个可行的。 不知道它有多经济,但它确实有效。

    $documents = $job->diary()
            ->with('job')
            ->join('documents', 'diary_id', '=', 'diaries.id')
            ->select(['documents.*'])
            ->paginate(15);
    

    如果有人有更好的解决方案,请分享。

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 2021-06-17
      • 2016-07-01
      • 2015-03-26
      • 2019-06-27
      • 2016-02-26
      • 2019-12-09
      • 2021-05-29
      • 1970-01-01
      相关资源
      最近更新 更多