如何将原生PHP SQL语句转换为Laravel查询构建器语句
最优实现(推荐,自动防SQL注入,可读性高)
你原来的SQL是隐式内连接三张表,用Laravel查询构建器显式写内连接的实现如下:
use Illuminate\Support\Facades\DB; // 查询逻辑 $topics = DB::table('topics') ->select('topic_id', 'topic_subject', 'cat_name', 'user_name', 'topic_date') // 关联分类表 ->join('categories', 'topics.topic_cat', '=', 'categories.cat_id') // 关联用户表 ->join('users', 'topics.topic_by', '=', 'users.user_id') // 过滤分类,Laravel自动做参数绑定,避免SQL注入 ->where('topics.topic_cat', $topicCat) ->orderByDesc('topic_date') ->limit(10) ->get();
查询结果返回的是Laravel集合实例,你可以直接遍历使用,需要数组的话追加调用->toArray()即可。
其他参考写法
1. 隐式连接写法(和你原SQL逻辑完全对齐,可读性低不推荐)
如果要完全复刻你原来的隐式连接写法,注意字段对比要使用whereColumn方法,避免把字段名识别为字符串值:
$topics = DB::table('topics', 'categories', 'users') ->select('topic_id', 'topic_subject', 'cat_name', 'user_name', 'topic_date') ->whereColumn('topics.topic_by', 'users.user_id') ->whereColumn('topics.topic_cat', 'categories.cat_id') ->where('topics.topic_cat', $topicCat) ->orderByDesc('topic_date') ->limit(10) ->get();
2. 模型关联写法(如果定义了Eloquent模型推荐用)
如果你已经创建了Topic、Category、User三个Eloquent模型,可以先在Topic模型中定义关联:
// app/Models/Topic.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Topic extends Model { // 关联分类 public function category() { return $this->belongsTo(Category::class, 'topic_cat', 'cat_id'); } // 关联发布用户 public function user() { return $this->belongsTo(User::class, 'topic_by', 'user_id'); } }
之后查询可以直接用预加载关联的方式,代码更简洁:
use App\Models\Topic; $topics = Topic::select('topic_id', 'topic_subject', 'topic_date', 'topic_cat', 'topic_by') ->with(['category:cat_id,cat_name', 'user:user_id,user_name']) ->where('topic_cat', $topicCat) ->orderByDesc('topic_date') ->limit(10) ->get();
这种方式返回的结果会把分类和用户信息作为嵌套属性挂载到话题对象下,更符合面向对象的操作习惯。
内容的提问来源于stack exchange,提问作者XxRoKeTfAcExX
相关产品推荐
相关产品推荐

