蛮力的方法是尝试一个User::selectRaw(...)
具有内置子查询的方法来获取用户的培训计数并将其公开为一个字段。
但是,有一种更内置的方法可以做到这一点。您可以预先加载关系(以避免 n+1 查询),并使用 DataTablesadd_column
方法添加计数。假设您的关系名为trainings
:
public function getData() {
$users = User::with('trainings')->select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->add_column('trainings', function($user) {
return $user->trainings->count();
})
->remove_column('id')
->make();
}
中列的名称add_column
应与加载的关系同名。如果出于某种原因使用不同的名称,则需要确保删除关系列,以便将其从数据数组中删除。例如:
return \Datatables::of($users)
->add_column('trainings_count', function($user) {
return $user->trainings->count();
})
->remove_column('id')
->remove_column('trainings')
->make();
编辑
不幸的是,如果您想在计数字段上订购,您将需要蛮力方法。包通过调用传递给方法->orderBy()
的对象来进行排序,因此查询本身需要排序的字段。Builder
of()
但是,即使您需要执行一些原始 SQL,它也可以变得更简洁一些。您可以添加将添加关系计数的模型范围。例如,将以下方法添加到您的 User 模型中:
注意:以下函数仅适用于 hasOne/hasMany 关系。请参阅Edit 2
下面的更新功能来处理所有关系。
public function scopeSelectRelatedCount($query, $relationName, $fieldName = null)
{
$relation = $this->$relationName(); // ex: $this->trainings()
$related = $relation->getRelated(); // ex: Training
$parentKey = $relation->getQualifiedParentKeyName(); // ex: users.id
$relatedKey = $relation->getForeignKey(); // ex: trainings.user_id
$fieldName = $fieldName ?: $relationName; // ex: trainings
// build the query to get the count of the related records
// ex: select count(*) from trainings where trainings.id = users.id
$subQuery = $related->select(DB::raw('count(*)'))->whereRaw($relatedKey . ' = ' . $parentKey);
// build the select text to add to the query
// ex: (select count(*) from trainings where trainings.id = users.id) as trainings
$select = '(' . $subQuery->toSql() . ') as ' . $fieldName;
// add the select to the query
return $query->addSelect(DB::raw($select));
}
将该范围添加到您的 User 模型后,您的 getData 函数将变为:
public function getData() {
$users = User::select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->selectRelatedCount('trainings')
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->remove_column('id')
->make();
}
如果您希望计数字段具有不同的名称,您可以将字段的名称作为第二个参数传递给selectRelatedCount
范围(例如selectRelatedCount('trainings', 'training_count')
)。
编辑 2
上述方法存在几个问题scopeSelectRelatedCount()
。
首先,调用 to$relation->getQualifiedParentKeyName()
只会对 hasOne/hasMany 关系起作用。这是该方法定义为的唯一关系public
。所有其他关系都将此方法定义为protected
. 因此,将此范围与不是 hasOne/hasMany 的关系一起使用会引发Illuminate\Database\Query\Builder::getQualifiedParentKeyName()
异常。
其次,生成的计数 SQL 并不是对所有关系都正确。同样,它对于 hasOne/hasMany 来说可以正常工作,但是手动生成的 SQL 对于多对多关系 (belongsToMany) 根本不起作用。
但是,我确实找到了解决这两个问题的方法。在查看了关系代码确定异常原因后,我发现 Laravel 已经提供了一个公共方法来为一个关系生成计数 SQL getRelationCountQuery()
:. 适用于所有关系的更新范围方法是:
public function scopeSelectRelatedCount($query, $relationName, $fieldName = null)
{
$relation = $this->$relationName(); // ex: $this->trainings()
$related = $relation->getRelated(); // ex: Training
$fieldName = $fieldName ?: $relationName; // ex: trainings
// build the query to get the count of the related records
// ex: select count(*) from trainings where trainings.id = users.id
$subQuery = $relation->getRelationCountQuery($related->newQuery(), $query);
// build the select text to add to the query
// ex: (select count(*) from trainings where trainings.id = users.id) as trainings
$select = '(' . $subQuery->toSql() . ') as ' . $fieldName;
// add the select to the query
return $query->addSelect(DB::raw($select));
}
编辑 3
此更新允许您将闭包传递给将修改添加到选择字段的计数子查询的范围。
public function scopeSelectRelatedCount($query, $relationName, $fieldName = null, $callback = null)
{
$relation = $this->$relationName(); // ex: $this->trainings()
$related = $relation->getRelated(); // ex: Training
$fieldName = $fieldName ?: $relationName; // ex: trainings
// start a new query for the count statement
$countQuery = $related->newQuery();
// if a callback closure was given, call it with the count query and relationship
if ($callback instanceof Closure) {
call_user_func($callback, $countQuery, $relation);
}
// build the query to get the count of the related records
// ex: select count(*) from trainings where trainings.id = users.id
$subQuery = $relation->getRelationCountQuery($countQuery, $query);
// build the select text to add to the query
// ex: (select count(*) from trainings where trainings.id = users.id) as trainings
$select = '(' . $subQuery->toSql() . ') as ' . $fieldName;
$queryBindings = $query->getBindings();
$countBindings = $countQuery->getBindings();
// if the new count query has parameter bindings, they need to be spliced
// into the existing query bindings in the correct spot
if (!empty($countBindings)) {
// if the current query has no bindings, just set the current bindings
// to the bindings for the count query
if (empty($queryBindings)) {
$queryBindings = $countBindings;
} else {
// the new count query bindings must be placed directly after any
// existing bindings for the select fields
$fields = implode(',', $query->getQuery()->columns);
$numFieldParams = 0;
// shortcut the regex if no ? at all in fields
if (strpos($fields, '?') !== false) {
// count the number of unquoted parameters (?) in the field list
$paramRegex = '/(?:(["\'])(?:\\\.|[^\1])*\1|\\\.|[^\?])+/';
$numFieldParams = preg_match_all($paramRegex, $fields) - 1;
}
// splice into the current query bindings the bindings needed for the count subquery
array_splice($queryBindings, $numFieldParams, 0, $countBindings);
}
}
// add the select to the query and update the bindings
return $query->addSelect(DB::raw($select))->setBindings($queryBindings);
}
使用更新的范围,您可以使用闭包来修改计数查询:
public function getData() {
$users = User::select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->selectRelatedCount('trainings', 'trainings', function($query, $relation) {
return $query
->where($relation->getTable().'.is_creator', false)
->where($relation->getTable().'.is_speaker', false)
->where($relation->getTable().'.was_absent', false);
})
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->remove_column('id')
->make();
}
注意:在撰写本文时,bllim/laravel4-datatables-package 数据表包在选择字段的子查询中存在参数绑定问题。数据将正确返回,但计数不会(“显示 0 到 0 个条目”)。我在这里详细说明了这个问题。这两个选项是使用该问题中提供的代码手动更新数据表包,或者不使用 count 子查询中的参数绑定。用于whereRaw
避免参数绑定。