我有一個User
模型,其中包含屬性type
以及其他屬性。類型用於識別父母和兒童。Laravel:基於雄辯關係獲取用戶
父母和子女(學生)有多對多的關係。 同時學生屬於一個或多個組(模型Group
)。
用戶模型
/**
* 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();
問: 現在我想找到這些學生的家長。但我無法爲此建立一個雄辯的查詢。我該怎麼做?
注:我可以從上面的查詢讓學生收集和運行foreach
循環才能得到父母的,像這樣
$parents = new Collection;
foreach($students as $student) {
foreach($student->parents as $parent) {
$parents->push($parent);
}
}
$parents = $parents->unique();
但我需要一個Builder
對象,而不是Collection
因爲我使用Datatables server side processing與Yajra/datatables 。
使用User :: student() - > with('parents')。這是關係的急切加載https://laravel.com/docs/5.3/eloquent-relationships#eager-loading – Silwerclaw
但這不會直接給我父母。他們將在嵌套關係中。我更喜歡爲父母獲得一個'Builder'對象。 – linuxartisan
ok - 然後你可以加載你的學生,然後調用$ students-> load(['parents' - > function($ query){//根據需要修改你的構建器}]) – Silwerclaw