Laravel模型使用ltree的postgresql`subpath`函数获得子路径

问题描述 投票:0回答:1

我在名为breadcrumbs的Postgresql服务器上具有下表:

id SERIAL path VARCHAR(300)

带有以下示例数据:

id | path
--- | ---
1 | animes.like.hentai
2 | animes.dislike.hentai
3 | animes.like.shonen
4 | animes.like.action

并且使用以下雄辩的模型进行建模:

<?php declare(strict_types=1);

namespace App\Model;
use Illuminate\Database\Eloquent\Model as BaseModel;

class Breadcrumbs extends BaseModel
{
   protected $table = 'breadcrumbs';

   // 
}

而且我想在不使用sql的情况下执行以下选择:

select * from breadcrumbs where subpath(et_location_desc.path, 0, 1) != 'hentai'

到目前为止,我尝试使用以下代码:

Breadcrumbs::where("subpath(path, 0, 1)","hentai")->all();

但出现以下错误:

Illuminate/Database/QueryException with message 'SQLSTATE[42703]: Undefined column: 7 ERROR:  column "subpath(path, 0, 1)" does not exist
LINE 1: select * from "breadcrumbs" where "subpath(path, 0, 1)"...
                                               ^ (SQL: select * from "breadcrumbs" where "subpath(path, 0, 1)" = hentai '

意味着where()方法的第一个参数是自动引用的,假定它是一列而不是函数。

所以我如何扩展模型的查询生成器或按原样使用上面的代码来执行正确的选择?

postgresql eloquent laravel-5.6
1个回答
0
投票

在此answer中看到的相同原则也适用于此处,而不是:

Breadcrumbs::where("subpath(path, 0, 1)","hentai")->all();

用途:

Breadcrumbs::where(DB::raw("subpath(path, 0, 1)"),"hentai")->all();

如在文档中所见,您可以使用DB:raw来绕过将列名用作fisrt参数的限制。

© www.soinside.com 2019 - 2024. All rights reserved.