User
モデルの属性は、他の属性の中でもtype
です。タイプは、親のとの子を識別するために使用されます。Laravel:Eloquentの関係に基づいてユーザーを取得する
親子(生徒)は多対多の関係を持っています。 また、学生はグループ(モデルGroup
)に属しています。
Userモデル
/**
* Filter the scope of users to student type.
*
* @param $query
*/
public function scopeStudent($query){
$query->where('type', '=', 'std');
}
/**
* Filter the scope of users to parent type.
*
* @param $query
*/
public function scopeParent($query){
$query->where('type', '=', 'prt');
}
/**
* List of groups the user is associated with.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function groups(){
return $this->belongsToMany('\App\Group', 'group_user_assoc')
->withTimestamps();
}
/**
* List of students associated with the user(parent).
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function children(){
return $this->belongsToMany('\App\User', 'student_parent_assoc', 'parent_id', 'student_id')
->withPivot('relation');
}
/**
* List of parents associated with the user(student).
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function parents(){
return $this->BelongsToMany('\App\User', 'student_parent_assoc', 'student_id', 'parent_id')
->withPivot('relation');
}
前述の関係が正しく機能しています。
以下は私の関連テーブルです。
student_parent_assoc
----------------------
+------------+------------------+------+-----+
| Field | Type | Null | Key |
+------------+------------------+------+-----+
| student_id | int(10) unsigned | NO | PRI |
| parent_id | int(10) unsigned | NO | PRI |
| relation | varchar(25) | YES | |
+------------+------------------+------+-----+
group_user_assoc
----------------------
+------------+------------------+------+-----+
| Field | Type | Null | Key |
+------------+------------------+------+-----+
| group_id | int(10) unsigned | NO | MUL |
| user_id | int(10) unsigned | NO | MUL |
| created_at | timestamp | NO | |
| updated_at | timestamp | NO | |
+------------+------------------+------+-----+
親と一緒にグループに所属していない学生を探す必要があります。私はそう
$students = User::student()
->whereDoesntHave('groups')
->get();
質問のような学生を見つけるために管理している:は は今、私はこれらの学生の両親を見つけたいです。しかし、私は同じもののための雄弁なクエリを構築することはできません。どうすればいいのですか?
注:私は、クエリ上から生徒のコレクションを取得し、その
$parents = new Collection;
foreach($students as $student) {
foreach($student->parents as $parent) {
$parents->push($parent);
}
}
$parents = $parents->unique();
のように両親を取得するためにforeach
ループを実行します。しかし、私はYajra/datatablesとDatatables server side processingを使用していますように私はBuilder
対象としませCollection
を必要とすることができます。
は、User :: student() - > with( 'parents')を使用します。これは関係の熱心なロードですhttps://laravel.com/docs/5.3/eloquent-relationships#eager-loading – Silwerclaw
しかし、それは私に両親を直接与えることはありません。彼らは入れ子にされた関係の中にあります。私は親のための 'Builder'オブジェクトを取得することを好むでしょう。 – linuxartisan
ok - 学生を読み込んだ後に、$ students-> load(['parents' - > function($ query){//必要に応じてビルダーを変更}]) – Silwerclaw