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

求助:将指定原生SQL转换为Laravel查询构造器

Convert Your Raw SQL to Laravel Query Builder

Hey there! Let's turn that raw SQL into clean, safe Laravel Query Builder code. First, let's clarify what your original query does: it fetches rows from the shelf table where each of your three values ($col1, $col2, $col3) appears in at least one of the columns column1 through column5.

The Query Builder Version

Here's the equivalent code, with proper parameter binding to avoid SQL injection (way safer than your original string concatenation!):

// Using Query Builder directly
$shelfRecords = DB::table('shelf')
    // First condition group: $col1 exists in any of column1-column5
    ->where(function ($query) use ($col1) {
        $query->where('column1', $col1)
              ->orWhere('column2', $col1)
              ->orWhere('column3', $col1)
              ->orWhere('column4', $col1)
              ->orWhere('column5', $col1); // Note: Your raw SQL had duplicate column4 for $col1, I adjusted to column5—fix this if it was intentional!
    })
    // Second condition group: $col2 exists in any of column1-column5
    ->where(function ($query) use ($col2) {
        $query->where('column1', $col2)
              ->orWhere('column2', $col2)
              ->orWhere('column3', $col2)
              ->orWhere('column4', $col2)
              ->orWhere('column5', $col2);
    })
    // Third condition group: $col3 exists in any of column1-column5
    ->where(function ($query) use ($col3) {
        $query->where('column1', $col3)
              ->orWhere('column2', $col3)
              ->orWhere('column3', $col3)
              ->orWhere('column4', $col3)
              ->orWhere('column5', $col3);
    })
    ->get();

Bonus: Using Eloquent Model

If you have an Eloquent model for the shelf table (e.g., Shelf.php), you can rewrite it even cleaner:

$shelfRecords = Shelf::query()
    ->where(function ($query) use ($col1) {
        // Same condition group as above
    })
    ->where(function ($query) use ($col2) {
        // Same condition group as above
    })
    ->where(function ($query) use ($col3) {
        // Same condition group as above
    })
    ->get();

Quick Notes

  • I fixed a potential typo in your original SQL: the first condition group had column4 = '$col1' twice. I changed the second instance to column5—if that was intentional, just swap it back to column4.
  • The use ($col1) syntax passes your variables into the closure so the query can access them.
  • Laravel automatically handles parameter binding here, so you don't have to worry about SQL injection risks like you do with raw string concatenation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:02:46