【问题标题】:Laravel 5.0 Queries Using Query Builder with JoinsLaravel 5.0 查询使用带有连接的查询生成器
【发布时间】:2015-05-09 23:18:12
【问题描述】:

我有一个 MySQL 查询,我想以 Laravel 5 的查询生成器格式实现它。

我有表格 Items 和 FaceOff。在我的 Laravel 控制器中,我引用了 namespace/Items 和 namespace/FaceOff 模型。

查询:

select i1.id as id1, i2.id as id2
from items i1 
join
     items i2 
left join
     faceoff f
     on (f.wonid = i1.id and f.lostid = i2.id and userid = '1') or
        (f.wonid = i2.id and f.lostid = i1.id and userid = '1')
where f.wonid is null and i1.id <> i2.id 
order by rand()
limit 1;

我遇到的问题是如何加入嵌套查询,以及如何为表使用别名。例如,这个简单的查询:

$items = Items::select('id as id1')

我可以为列名设置别名,但不知道如何为整个查询的结果设置别名。

简而言之,我正在尝试抓取 2 个在“正面交锋”中没有遇到过的随机物品。可以将其视为将两个竞争对手配对 - 每个竞争对手应该只支付另一个竞争对手一次。因此,查询应返回 ID1 和 ID2。这些应该是不同的 ID,并且彼此之间没有赢或输。

问题:

谁能帮我把它翻译成 Laravel 的查询构建器格式?我怀疑我必须使用 DB::raw 表达式。

我尝试使用 DB::Raw 表达式但失败了,它给出了关于未包含 DB 模型的错误。我也很犹豫是否将系统开放给 SQL 注入,无论如何,都在努力解决连接问题。

提前感谢迷路的人。

【问题讨论】:

    标签: mysql laravel eloquent laravel-5


    【解决方案1】:

    您的代码中唯一棘手的部分是不寻常的join。其他部分只是简单的Query\Builder方法:

    // you could use model query, but it makes little sense in this case
    // Items::from('items as i1')->join...
    DB::table('items as i1')
      ->join( DB::raw('items as i2 left join faceoff as f'), function ($j) {
        $j->on('f.wonid', '=', 'i1.id')
            ->on('f.lostid', '=', 'i2.id')
            ->where('userid', '=', 1)
          ->orOn('f.wonid', '=', 'i2.id')
            ->on('f.lostid', '=', 'i1.id')
            ->where('userid', '=', 1);
    
      })->whereNull('f.wonid')
      ->where('i1.id', '<>', 'i2.id')
      ->orderByRaw('rand()')
      ->take(1)
      ->select('i1.id as id1', 'i2.id as id2')
      ->get();
    

    【讨论】:

    • 怎么样..和同一张桌子
    猜你喜欢
    • 2014-12-06
    • 2020-03-12
    • 2016-11-16
    • 2022-01-20
    • 2014-05-13
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多