在Laravel的where子句中嵌套的eager加载

时间:2016-03-02 07:07:00

标签: orm eloquent laravel-5.1 eager-loading

我想知道无论如何使用Eloquent在Laravel中编写这样的查询。我的意思是我可以在where子句中进行切换加载。我从最后一天开始被困在这里,我真的想这样做。所以需要建议。

        $notifications = Notification::where('user_id',Auth::user()->id)
            ->where('is_try', '!=', Config::get('constants.NOTIFICATION_AGAINST_JOB_TURN_DOWN'))
            ->where('is_try', '!=', Config::get('constants.NOTIFICATION_AGAINST_JOB_EXPIRED'))
            ->where(function($query) {
                $query->where(function($query) {
                    $query->where('message', '!=', 'job_post')
                        ->with(['suggestion' => function ($query) {
                            $query->with(['job' => function ($query) {
                                $query->with('company');
                            }]);
                        }]);
                    })
                    ->orWhere(function($query){
                        $query->where('message','job_post')
                        ->with(['job' => function ($query) {
                            $query->with('company');
                        }]);
                });
            })
            ->orderBy('notifications.created_at','desc')
            ->get();

1 个答案:

答案 0 :(得分:0)

据我所知,您可以加载$query->load('company');之类的关系,而不是$query->with('company');

你也可以像这样加载多个/嵌套关系。

Notification::with([
                    'rel'=>function($q){ $q->where()... //can add up where, orderby etc clauses like this},
                     rel.profile, 
                     rel.profile.images, 
                     rel.profile.images.location

                  ])->wehre()....

你也可以这样做,

$course_orignal     =   Courses::find($course_id);

$course_orignal->load('quizzes','quizzes.questions', 'chapters','chapters.quizzes.questions','chapters.lessons','chapters.lessons.quizzes','chapters.lessons.quizzes.questions');