Laravel雄辩的多重关系

时间:2019-07-05 01:48:07

标签: laravel eloquent

仅当它具有所有必要的关系时,我才需要它。

此刻我的代码:

StudentController

$student = Student::with('inscriptions','inscriptions.classroom')
                    ->find($request->user()->id);

学生

public function inscriptions()
{
    return $this->hasMany('App\InscribedStudent');
}

InscribedStudent -注意:“注册已打开”

public function classroom()
{
    return $this->hasOne('App\Classroom', 'id')->where('registration_open', true);
}

Json Return 尚未打开注册的时间

{
    "inscriptions": [
        {
            "id": 1,
            "student_id": 1,
            "classroom_id": 1,
            "deleted_at": null,
            "created_at": "2019-07-04 23:34:48",
            "updated_at": "2019-07-04 23:34:48",
            "classroom": null
        }
    ]
}

我想做类似的事情,因为如果我没有教室,我不需要对象InscribedStudent。

public function inscriptions()
{
    return $this->hasMany('App\InscribedStudent')
                ->hasOne('App\Classroom', 'id')
                ->where('registration_open', true);
}

1 个答案:

答案 0 :(得分:1)

您可以使用has()whereHas()来检查教室是否存在。

https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

// this will only get students that have a classroom through inscriptions
$students = Student::has('incriptions.classroom')
                   ->with('inscriptions.classroom')
                   ->get();

// this will get students, but only fetch inscriptions if there is a classroom
$students = Student::with(['inscriptions' => function($inscriptionQuery) {
                         $inscriptionQuery->has('classroom')->with('classroom');
                     }])
                     ->get();

如果您想使用它,也可以在Student模型上创建自定义范围。

// this will only get students that have a classroom through inscriptions
public function scopeHasClassroom($query)
{
    $query->has('inscriptions.classroom')
          ->with('inscriptions.classroom');
}

// this will get students, but only fetch inscriptions if there is a classroom
public function scopeHasClassroom($query)
{
    $query->with(['inscriptions' => function($inscriptionQuery) {
        $inscriptionQuery->has('classroom')->with('classroom');
    }]);
}

然后您可以像这样调用自定义范围:

$students = Student::hasClassroom()->get();

https://laravel.com/docs/5.8/eloquent#query-scopes