/**
* 转发动态和资讯数量统计
*/
public function forwardCounts(FeedModel $feedModel)
{
//统计动态转发的id
$feeds=$feedModel->where('forward_type','feeds')
->pluck('forward_id')->toArray();
//统计动态转发的id出现的次数
$feeds=array_count_values($feeds); //key值对应动态id value值为转发的次数
foreach($feeds as $key => $value){
$multipleData[] = [ 'id'=>$key,
'forward_counts'=>$value, ]; } //批量更新数据库数据
$res = $this->updateBatch('feeds',$multipleData); if(!$res) echo '更新出错'; //统计资讯转发的id
$news=$feedModel->where('forward_type','news')
->pluck('forward_id')->toArray();
//统计资讯转发的id出现的次数
$news=array_count_values($news); //key值对应动态id value值为转发的次数
foreach($news as $key => $value){
$multipleDatas[] = [ 'id'=>$key,
'forward_counts'=>$value, ]; } //批量更新数据库数据
$ress = $this->updateBatch('news',$multipleDatas); if(!$ress) echo '更新出错'; return '更新成功'; } //同时更新多个记录,参数,表名,数组(别忘了在一开始use DB;)
public function updateBatch($tableName = "", $multipleData = array()){ if( $tableName && !empty($multipleData) ) { // column or fields to update
$updateColumn = array_keys($multipleData[0]);
$referenceColumn = $updateColumn[0]; //e.g id
unset($updateColumn[0]);
$whereIn = ""; $q = "UPDATE ".$tableName." SET ";
foreach ( $updateColumn as $uColumn ) {
$q .= $uColumn." = CASE "; foreach( $multipleData as $data ) {
$q .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$uColumn]."' ";
}
$q .= "ELSE ".$uColumn." END, ";
}
foreach( $multipleData as $data ) {
$whereIn .= "'".$data[$referenceColumn]."', ";
}
$q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (". rtrim($whereIn, ', ').")"; // Update
return DB::update(DB::raw($q)); } else {
return false;
} }