【问题标题】:Laravel - Two or more alias to same table in query builderLaravel - 查询构建器中同一个表的两个或多个别名
【发布时间】:2019-04-05 22:44:46
【问题描述】:

我需要使用查询生成器在 Laravel 中复制 SQL 查询,但我不知道如何为同一张表定义多个别名。

我的这个SQL 查询工作正常。

select b.url as url, b.id as id
from item a, item b
where a.type = 'big'
AND a.published = 1
AND b.parent_id = a.id
AND b.published = 1

这是 Laravel 的尝试:

$query = DB::table('item as a, item as b');
$query->where('a.type', '=', 'big');
$query->where('a.published', '=', 1);
$query->where('b.parent_id', '=', 'a.id');
$query->where('b.published', '=', 1);

我也尝试过:

$query = DB::table('item');
$query->fromRaw('item a, item b');
$query->where('a.type', '=', 'big');
$query->where('a.published', '=', 1);
$query->where('b.parent_id', '=', 'a.id');
$query->where('b.published', '=', 1);

我需要使用查询生成器,因为我在接下来的步骤中需要一些条件,这就是为什么我不能使用简单的“hasMany”关系。

更新items 表详细信息:

【问题讨论】:

  • 你的意思是'item1 as a'和'item2 as b'。对吗?
  • 嗯,同一张表为什么需要两个别名?
  • 请把你的表结构。可能需要使用join函数。

标签: php mysql laravel eloquent


【解决方案1】:

#Raw 表达式

有时您可能需要在查询中使用原始表达式。这些表达式将作为字符串注入到查询中,因此请注意不要创建任何 SQL 注入点!要创建原始表达式,您可以使用DB::raw 方法:

https://laravel.com/docs/4.2/queries#raw-expressions

$query = DB::table(DB::raw('item as a, item as b'))
              ->where('a.type', '=', 'big')
              ->where('a.published','=',1)
              ->where('b.parent_id','=', DB::raw('a.id'))
              ->select('b.url','b.id')
              ->get();

【讨论】:

  • 我猜你需要修复->where('b.parent_id','=',DB::raw('a.id'))
猜你喜欢
  • 2019-01-24
  • 2021-03-25
  • 2013-05-02
  • 2017-06-29
  • 2018-12-16
  • 1970-01-01
  • 2015-12-10
  • 2022-01-01
  • 2018-07-20
相关资源
最近更新 更多