gpt4 book ai didi

php - Laravel - 查询构建器中同一个表的两个或多个别名

转载 作者:行者123 更新时间:2023-11-29 04:32:39 24 4
gpt4 key购买 nike

我需要使用查询构建器在 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 表详细信息:

Items table

最佳答案

#原始表达式

有时您可能需要在查询中使用原始表达式。这些表达式将作为字符串注入(inject)到查询中,因此请注意不要创建任何 SQL 注入(inject)点!要创建原始表达式,您可以使用 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();

关于php - Laravel - 查询构建器中同一个表的两个或多个别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55533361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com