我有一个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