在Laravel中,可以使用`where`方法来添加查询条件,但是每次添加`where`条件时,都会在查询构造器中持久化这些条件,直到你手动重置它们。所以,如果你想在下一次查询中清除上次查询的`where`条件,有以下几种选择:
1. 使用`getQuery`方法:
可以使用`getQuery`方法获取查询构造器的实例,并使用`wheres`属性来获取所有`where`条件,然后使用`reset`方法重置条件。
$query = Model::where('column1', 'value1')->orWhere('column2', 'value2');
// 获取查询构造器实例
$builder = $query->getQuery();
// 清除所有 where 条件
$builder->wheres = [];
2. 创建新的查询构造器实例:
$query = Model::query(); // 创建新的查询构造器实例
$query = $query->where('column1', 'value1')->orWhere('column2', 'value2');
// 下一次查询时,创建新的查询构造器实例
$query = Model::query();
3. 使用闭包:
$query = Model::query();
$query = $query->where(function ($query) {
$query->where('column1', 'value1')->orWhere('column2', 'value2');
});
// 下一次查询时,不添加任何条件
$query = Model::query();
4.如果你想清空某个字段的查询条件,可以使用`getQuery`方法获取查询构造器的实例,并使用`wheres`属性来获取所有的`where`条件,然后遍历条件数组,找到需要清空的条件并删除。
以下是一个示例代码片段,演示如何清空某个字段的查询条件:
$query = Model::where('column1', 'value1')->where('column2', 'value2')->where('column3', 'value3');
// 获取查询构造器实例
$builder = $query->getQuery();
// 获取所有 where 条件
$wheres = $builder->wheres;
// 遍历条件数组
foreach ($wheres as $key => $where) {
// 检查条件是否为字段 'column2'
if (isset($where['column']) && $where['column'] === 'column2') {
// 删除条件
unset($wheres[$key]);
}
}
// 重新设置查询构造器的 wheres 属性
$builder->wheres = $wheres;
// 执行查询
$results = $query->get();
在上面的示例中,我们首先获取查询构造器实例,然后获取所有的`where`条件,并遍历条件数组。如果条件的字段等于 `'column2'`,我们就删除该条件。最后,我们重新设置查询构造器的 `wheres` 属性,并执行查询。
请根据你的具体需求修改示例代码,以适应你的查询条件和模型。
public function likeVisit(Request $request)
{
$userId = $request->user()->id;
$params = $request->all();
$page = $params['page'] ?? self::PAGE;
$limit = $params['limit'] ?? self::LIMIT;
$type = $params['type'] ?? 1; //1 我喜欢的 2喜欢我的 3最近来访 4互相喜欢
$zSetCache = new ZsetCache();
$stringCache = new SysConfigStringCache();
$cacheKey = 'Visit:' . $type . '_' . $page . '_' . $limit . '_' . $userId;
$stringCache->setKeyParameter([$cacheKey]);
$cacheData = $stringCache->get();
if ($cacheData) {
return $this->success(json_decode($cacheData, 320));
} else {
$info = [
'my_like_user' => [],
'like_me_user' => [],
'visit_user' => [],
'each_like_list' => [],
];
$myLikeUserIds = UserLike::myLikeUserIds($userId);
$likeMeUserIds = UserLike::likeMeUserIds($userId);
$eachLikeIds = array_intersect($myLikeUserIds, $likeMeUserIds);
//我已经解锁的用户[喜欢我的 最近来访]
$myUnLockId = [];
if ($type == 2 || $type == 3) {
$myUnLockId = UserUnlock::getLockStatus(['user_id' => $userId]);
}
$select = ['nickname', 'birthday', 'avatar', 'stature', 'location_city_id', 'user_id', 'like_user_id', 'ip'];
$query = User::query()->select($select);
if ($type == 1) { //1.我喜欢的
$myLike = $query->leftJoin('meet_user_like', 'meet_user.id', '=', 'meet_user_like.like_user_id')
->where(['user_id' => $userId, 'meet_user_like.type' => 1])
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->orderBy('meet_user_like.id', 'desc')
->offset($page * $limit)
->limit($limit)
->get();
$myLike = !empty($myLike) ? $myLike->toArray() : [];
foreach ($myLike as &$item) {
$item['each_like'] = in_array($item['like_user_id'], $likeMeUserIds);
}
$info['my_like_user'] = (new UserLike())->formatUser($myLike);
} elseif ($type == 2) { //2.喜欢我的
$query = $query->leftJoin('meet_user_like', 'meet_user.id', '=', 'meet_user_like.user_id')
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.identity_status', 1)
->where('meet_user.score', '>', 70)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->where(['like_user_id' => $userId, 'meet_user_like.type' => 1]);
})
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.status', 1)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->where(['like_user_id' => $userId, 'meet_user_like.type' => 1]);
})
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.vip_status', 1)
->where(['like_user_id' => $userId, 'meet_user_like.type' => 1])
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF);
});
//年龄范围
if (isset($params['age_min']) && !empty($params['age_min']) && isset($params['age_max']) && !empty($params['age_max'])) {
$ageMin = now()->subYears($params['age_max'])->toDateString();
$ageMax = now()->subYears($params['age_min'])->toDateString();
$query->where('birthday', '>=', $ageMin);
$query->where('birthday', '<=', $ageMax);
}
//城市
if (isset($params['location_city_id']) && !empty($params['location_city_id'])) {
$query->where('location_city_id', $params['location_city_id']);
}
//身高
if (isset($params['stature_min']) && !empty($params['stature_min']) && isset($params['stature_max']) && !empty($params['stature_max'])) {
$query->where('stature', '>=', $params['stature_min']);
$query->where('stature', '<=', $params['stature_max']);
}
//学历
if (isset($params['education_level']) && !empty($params['education_level'])) {
$query->where('education_level', '>=', $params['education_level']);
}
$likeMe = $query->orderBy('meet_user_like.id', 'desc')
->offset($page * $limit)
->limit($limit)
->get();
$likeMe = !empty($likeMe) ? $likeMe->toArray() : [];
foreach ($likeMe as &$item) {
$item['each_like'] = in_array($item['user_id'], $myLikeUserIds);
$item['lock_status'] = isset($myUnLockId[$item['user_id']]);
}
$info['like_me_user'] = (new UserLike())->formatUser($likeMe);
//销毁动态新增喜欢(红色标记样式)
$newLikeMeKey = 'Like:new_like_me_' . $userId;
$stringCache->del($newLikeMeKey);
} elseif ($type == 3) {//3最近来访
//销毁动态新增来访
$newVisitMeKey = 'Visit:new_visit_me_' . $userId;
$stringCache->del($newVisitMeKey);
//阅后即焚,将该成员销毁掉,避免影响新的值比对
$visitNumKey = 'Visit:new_visit_num';
$zSetCache->zRem($visitNumKey, $newVisitMeKey);
//3.最近来访
$tomorrow = Carbon::tomorrow()->toDateString();
$today = Carbon::today()->toDateString();
$yesterday = Carbon::yesterday()->toDateString();
$select = ['nickname', 'birthday', 'avatar', 'stature', 'location_city_id', 'user_id', 'visit_num', 'meet_user_visit.created_at as visit_time', 'ip'];
//$todayVisitKey = 'Visit:' . 'total_visit_ids_' . $userId;
//$todayVisitIds = $zSetCache->zRangeByScore($todayVisitKey, strtotime(date('Y-m-d')), time()); //今日访客ids
//$yesterdayVisitIds = $zSetCache->zRangeByScore($todayVisitKey, strtotime(date("Y-m-d", strtotime("-1 day"))), strtotime(date('Y-m-d'))); //昨日访客ids
//$historyVisitIds = $zSetCache->zRangeByScore($todayVisitKey, '-inf', strtotime(date("Y-m-d", strtotime("-1 day")))); //历史访客ids
$recentVisitData = [
'todayVisit' => [],
'yesterdayVisit' => [],
'historyVisit' => [],
];
/*$recentVisit = User::query()
->select($select)
->leftJoin('meet_user_visit', 'meet_user.id', '=', 'meet_user_visit.user_id')
->where('visited_id', $userId)
->where('avatar', '!=', '') // 过滤掉空头像用户
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.identity_status', 1)
->where('meet_user.score', '>', 70)
->where('visited_id', $userId)
->where('avatar', '!=', ''); // 附加条件
})
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.status', 1)
->where('visited_id', $userId)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->where('avatar', '!=', ''); // 附加条件
})
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.vip_status', 1)
->where('visited_id', $userId)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->where('avatar', '!=', ''); // 附加条件
})
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->orderBy('meet_user_visit.id', 'desc')
->offset($page * $limit)
->limit($limit)
->get();*/
$recentVisitQuery = User::query()->select($select)
->leftJoin('meet_user_visit', 'meet_user.id', '=', 'meet_user_visit.user_id')
->where(['visited_id' => $userId])
->where('avatar', '!=', '') //过滤掉空头像用户
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF) //没有注销的用户
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.identity_status', 1)
->where('meet_user.score', '>', 70)
->where('visited_id', $userId)
->where('avatar', '!=', ''); // 附加条件
})
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.status', 1)
->where('visited_id', $userId)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->where('avatar', '!=', ''); // 附加条件
})
->orWhere(function ($query) use ($userId) {
$query->where('meet_user.vip_status', 1)
->where('visited_id', $userId)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->where('avatar', '!=', ''); // 附加条件
})
->orderByDesc('meet_user_visit.created_at');
foreach ($recentVisitData as $key => $datum) {
if ($key == 'todayVisit') {
//今天访客
$todayVisit = $recentVisitQuery->where('meet_user_visit.created_at', '>', $today)->where('meet_user_visit.created_at', '<', $tomorrow)->get()->groupBy('user_id');
$todayVisit = $todayVisit->isNotEmpty() ? $todayVisit->toArray() : [];
$newTodayVisit = [];
foreach ($todayVisit as $todayItem) {
$visitUser = (array)$todayItem[0];
$visitUser['each_like'] = in_array($visitUser['user_id'], $eachLikeIds);
$visitUser['lock_status'] = isset($myUnLockId[$visitUser['user_id']]);
$newTodayVisit[] = $visitUser;
}
$recentVisitData['todayVisit'] = (new UserLike())->formatUser($newTodayVisit);
//dd($recentVisitData['todayVisit']);
} elseif ($key == 'yesterdayVisit') {
//昨天
//1. 获取查询构造器实例
$builder = $recentVisitQuery->getQuery();
//2. 获取所有 where 条件
$wheres = $builder->wheres;
$bindings = $builder->bindings;
//3. 遍历条件数组
foreach ($wheres as $key => $where) {
// 检查条件是否为字段 'column2'
if (isset($where['column']) && $where['column'] === 'meet_user_visit.created_at') {
//unset($wheres[$key]); // 删除条件
if ($wheres[$key]['operator'] == '>') {
$wheres[$key]['value'] = $yesterday;
$bindings['where'][$key] = $yesterday;
} elseif ($wheres[$key]['operator'] == '<') {
$wheres[$key]['value'] = $today;
$bindings['where'][$key] = $today;
}
}
}
//4. 重新设置查询构造器的 wheres 属性
$builder->wheres = $wheres;
$builder->bindings = $bindings;
// 清除所有 where 条件
// $builder->wheres = [];
//5. 执行查询
$yesterdayVisit = $builder->get()->groupBy('user_id');
//$builder = $recentVisitQuery->getQuery();
//dd($builder,$builder->bindings);
//$yesterdayVisit = $builder->where('meet_user_visit.created_at', '>', $yesterday)->where('meet_user_visit.created_at', '<', $today)->get()->groupBy('user_id');
$yesterdayVisit = $yesterdayVisit->isNotEmpty() ? $yesterdayVisit->toArray() : [];
$newYesterdayVisit = [];
foreach ($yesterdayVisit as $item) {
$visitUser = (array)$item[0];
$visitUser['each_like'] = in_array($visitUser['user_id'], $eachLikeIds);
$visitUser['lock_status'] = isset($myUnLockId[$visitUser['user_id']]);
$newYesterdayVisit[] = $visitUser;
}
$recentVisitData['yesterdayVisit'] = (new UserLike())->formatUser($newYesterdayVisit);
//dd( $recentVisitData['yesterdayVisit']);
} else {
//历史来访
//1. 获取查询构造器实例
$builder = $recentVisitQuery->getQuery();
//2. 获取所有 where 条件
$wheres = $builder->wheres;
$bindings = $builder->bindings;
//3. 遍历条件数组
foreach ($wheres as $key => $where) {
if (isset($where['column']) && $where['column'] === 'meet_user_visit.created_at') {
if ($wheres[$key]['operator'] == '>') {
unset($wheres[$key], $bindings['where'][$key]); // 删除条件
} else {
$wheres[$key]['value'] = $yesterday;
$bindings['where'][$key] = $yesterday;
}
}
}
//4. 重新设置查询构造器的 wheres 属性
$builder->wheres = $wheres;
$builder->bindings = $bindings;
//5. 执行查询
$historyVisit = $builder->get()->groupBy('user_id');
// $historyVisit = $recentVisitQuery->withoutGlobalScope('meet_user_visit.created_at')->where('meet_user_visit.created_at', '<', $yesterday)->offset($page * $limit)->limit($limit)->get()->groupBy('user_id');
$historyVisit = $historyVisit->isNotEmpty() ? $historyVisit->toArray() : [];
$newHistoryVisit = [];
foreach ($historyVisit as $item) {
$visitUser = (array)$item[0];
$visitUser['each_like'] = in_array($visitUser['user_id'], $eachLikeIds);
$visitUser['lock_status'] = isset($myUnLockId[$visitUser['user_id']]);
$newHistoryVisit[] = $visitUser;
}
$recentVisitData['historyVisit'] = (new UserLike())->formatUser($newHistoryVisit);
//dd( $recentVisitData['historyVisit']);
}
}
//dd($recentVisitData);
/*if ($recentVisit->isNotEmpty()) {
$recentVisit = $recentVisit->toArray();
$recentVisit = (new UserLike())->formatUser($recentVisit);
// dd($recentVisit);
$visitData = $yesterdayVisitData = $historyVisitData = [];
foreach ($recentVisit as $visit) {
$visit['each_like'] = in_array($visit['user_id'], $eachLikeIds);
$visit['lock_status'] = isset($myUnLockId[$visit['user_id']]);
if ($tomorrow > $visit['visit_time'] && $visit['visit_time'] > $today) {//今天访客
if (!isset($visitData[$visit['user_id']])) {
$visitData[$visit['user_id']] = $visit;
$recentVisitData['todayVisit'][] = $visit;
}
} elseif ($today > $visit['visit_time'] && $visit['visit_time'] > $yesterday) { //昨天
if (!isset($yesterdayVisitData[$visit['user_id']])) {
$yesterdayVisitData[$visit['user_id']] = $visit;
$recentVisitData['yesterdayVisit'][] = $visit;
}
} elseif ($yesterday > $visit['visit_time']) {
if (!isset($historyVisitData[$visit['user_id']])) {
$historyVisitData[$visit['user_id']] = $visit;
$recentVisitData['historyVisit'][] = $visit;
}
}
}
unset($visitData, $yesterdayVisitData, $historyVisitData);
}*/
$info['visit_user'] = $recentVisitData;
unset($recentVisitData);
} elseif ($type == 4) { //4互相喜欢
//$eachLikeIds = array_intersect($myLikeUserIds, $likeMeUserIds);
$select = ['id as like_user_id', 'nickname', 'birthday', 'avatar', 'stature', 'location_city_id', 'ip'];
$eachLikeList = User::query()->select($select)
->where('meet_user.status', '<>', User::USER_STATUS_LOG_OFF)
->whereIn('meet_user.id', $eachLikeIds)
->offset($page * $limit)
->limit($limit)
->get();
$eachLikeList = !empty($eachLikeList) ? $eachLikeList->toArray() : [];
foreach ($eachLikeList as &$item) {
$item['user_id'] = $userId;
$item['each_like'] = true;
}
$info['each_like_list'] = (new UserLike())->formatUser(array_values($eachLikeList));
$info['each_like_count'] = count($eachLikeIds);
}
//缓存1小时
//$stringCache->set(json_encode($info, 320));
//$stringCache->expire(3600);
return $this->success($info);
}
}