mysql - Laravel 5.0 查询使用带连接的查询构建器

标签 mysql laravel eloquent laravel-5

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

我有表 Items 和 FaceOff。在我的 Laravel Controller 中,我引用了 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 表达式但失败了,它给出了关于未包含数据库模型的错误。我也对向 SQL 注入(inject)开放系统犹豫不决,无论如何,都在努力解决连接问题。

预先感谢迷路的人。

最佳答案

代码中唯一棘手的部分是不寻常的 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();

关于mysql - Laravel 5.0 查询使用带连接的查询构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28931193/

相关文章:

php - select内连接,sql和php的group_concat

php - SQL ORDER String (NumberOrder/CurrentYear) 来自两个表

php - 优化 SQL 查询

php - Laravel 图表 : Passing variable to handler function

Laravel 使用 eloquent 查询多个表

MySQL 随机查询生成器输出含义

php - Laravel 支持 return Redirect::back()->withFile() 吗?

php - 使用 Laravel 在 Docker Mysql 上连接被拒绝

mysql - Laravel - 按月获取数据

php - Laravel:错误 [PDOException]:无法在 MySQL 中找到驱动程序