Laravel 模型关联 hasManyThrough 中关联模型 分组并比较大小

现在有三个表

schools:
    id
    name

students:
    id
    name
    grade_id

grades:
    id
    name
    school_id

我在 School 模型定义了一个远程一对多的关系获取学校的学生(此处是举例,后面有简单的说明)

public function students()
    {
        return $this->hasManyThrough(
            Student::class,
            Grade::class,
                'school_id',
                'grade_id',
                'id',
                'id'
        );
    }

目前是这样实现的,数据表和模型简化了很多。大体是比较students和grades表的*_price大小,先拿到所有大于grades表中students的id集合。schools跟students通过id关联,最后拿到schools表的数据。

集合数据的处理由以下代码实现(省略了模型关联等代码)

    public function middleCollect($data)
    {
        $datas = [];
        foreach ($data as $key => $value){
            //取到students表数据,用了一对多关系
            $grades = $value->grade ?? null;
            //取到grades表数据,用了远程一对多关系
            $standGrades = $value->standGrade ?? null;
            if ($grades){
                $grades = $grades->mapWithKeys(function ($item) {
                    return [$item['oil_no'] => $item['my_price'] ?: $item['oil_price']];
                });
                $item['92#'] = $prices['92#'] ?? null;
                $item['95#'] = $prices['95#'] ?? null;
                $item['0#'] = $prices['0#'] ?? null;
                $item['98#'] = $prices['98#'] ?? null;
            }
            if ($standGrades){
                $standGrades = $standGrades->mapWithKeys(function ($item) {
                    return [$item['oil_name'] => $item['region_price'] ?? null];
                });
                $item['m92#'] = $markprices['92#'] ?? null;
                $item['m95#'] = $markprices['95#'] ?? null;
                $item['m0#'] = $markprices['0#'] ?? null;
            }
            if ($grades->get('92#') >$standGrades->get('92#') || $grades->get('95#') >$standGrades->get('95#') || $grades->get('0#') >$standGrades->get('0#')){
                array_push($datas,$value['id']);
            }
        }
        return $datas;
    }

写完代码后,想到官方文档中看到的代码

$user->posts()->where('active', 1)->get()

请问各位大佬,Eloquent 模型中能否用更优雅、简洁的方式实现。
比如:
1.如何以链式的方法直接拿到模型数据
2.在不使用foreach循环的前提下,还有哪些方式
3.Eloquent 查询这一块,优化有什么好的建议

希望大佬们能回答一下其中的一点,分享一下经验,谢谢

编程如作画,语言和框架只是我们的画笔
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1

大哥,前面的那段看得好熟悉,我还以为我走错地方了

5年前 评论
zulien (楼主) 5年前
小学毕业生 (作者) 5年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!