I have this relationship in my Department model:
public function subjects() {
return $this->hasMany('App\Models\Subject');
}
If I run App\Models\Department::with(["subjects"])->get(), I see the following results (simplified for the point):
Illuminate\Database\Eloquent\Collection {#912
all: [
App\Models\Department {#790 //Department
...
code: "A",
school_id: 1,
school: App\Models\School {#796 //School
...
code: "Z",
},
subjects: Illuminate\Database\Eloquent\Collection {#813
all: [
App\Models\Subject {#806 //Subject
...
code: "M",
department_id: 1,
department: App\Models\Department {#817 //Department (by eager loading)
...
code: "A",
school_id: 1,
school: App\Models\School {#823 //School
...
code: "Z",
},
},
},
...
],
},
},
...
],
}
Because I do not want any recursion, I tried running App\Models\Department::with(["subjects" => function($query){$query->select("id", "code")}])->get().
And all the Subjects are gone from the results, like so:
Illuminate\Database\Eloquent\Collection {#912
all: [
App\Models\Department {#790 //Department
...
code: "A",
school_id: 1,
school: App\Models\School {#796 //School
...
code: "Z",
},
subjects: Illuminate\Database\Eloquent\Collection {#813
all: [],
},
},
...
],
}
Then I tried the same ->with() structure (with $query->select()) on hasOne() relationships and those worked. I also tried on hasMany() relationships and all of those failed. Why is that so? And how can I add constraints to hasMany() eager loads?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire