You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Laravel Eloquent基于用户数据对职位数据做相关性排序?

Laravel Eloquent 按用户属性排序职位数据的实现

实现代码

先获取目标用户Doe的信息:

$user = User::where('name', 'Doe')->first();

下面两种方法都能实现需求,优先按用户的city_id匹配排序,再按grade_id匹配排序:

方法1:用orderByRaw简洁实现

直接通过原生SQL条件定义排序优先级,把和用户城市匹配的职位排前面,再筛选匹配用户等级的:

$jobs = Job::orderByRaw("city_id = ? DESC, grade_id = ? DESC", [$user->city_id, $user->grade_id])->get();

执行后得到的排序结果为:Data3 → Data4 → Data2 → Data1,完全符合需求。

方法2:DB::raw结合CASE语句拆分逻辑

如果需要更直观的逻辑拆分,用CASE语句定义排序权重:

use Illuminate\Support\Facades\DB;

$jobs = Job::orderBy(DB::raw("CASE WHEN city_id = {$user->city_id} THEN 0 ELSE 1 END"))
          ->orderBy(DB::raw("CASE WHEN grade_id = {$user->grade_id} THEN 0 ELSE 1 END"))
          ->get();

这个方法和方法1效果一致,只是逻辑拆分更清晰,方便后续扩展复杂排序规则。

相关搜索关键词

  • Laravel Eloquent custom order by condition
  • Laravel orderByRaw user-specific sorting
  • Laravel Eloquent sort by matching column values

内容的提问来源于stack exchange,提问作者Roodey21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:37:27