emiliopedrollo/laravel-postgres-extended-schema

Eloquent 扩展,增加了某些 PostgreSQL 功能

v4.11.1 2024-06-28 19:43 UTC

README

Build Status Maintainability Latest Stable Version Total Downloads Monthly Downloads License License

介绍

Laravel 9+ 的扩展 PostgreSQL 驱动程序,支持一些额外的 PostgreSQL 数据类型:hstore、uuid、几何类型(点、路径、圆、线、多边形...)以及支持 WITH [RECURSIVE] 子句

安装

在项目根目录简单运行 composer require emiliopedrollo/laravel-postgres-extended-schema

这样就完成了。

使用方法

SELECT 查询

使用 withExpression() 并提供一个查询构建器实例、一个 SQL 字符串或一个闭包

$posts = DB::table('p')
    ->select('p.*', 'u.name')
    ->withExpression('p', DB::table('posts'))
    ->withExpression('u', function ($query) {
        $query->from('users');
    })
    ->join('u', 'u.id', '=', 'p.user_id')
    ->get();

使用 withRecursiveExpression() 进行递归表达式

$query = DB::table('users')
    ->whereNull('parent_id')
    ->unionAll(
        DB::table('users')
            ->select('users.*')
            ->join('tree', 'tree.id', '=', 'users.parent_id')
    );

$tree = DB::table('tree')
    ->withRecursiveExpression('tree', $query)
    ->get();

您可以将表达式的列作为第三个参数提供

$query = 'select 1 union all select number + 1 from numbers where number < 10';

$numbers = DB::table('numbers')
    ->withRecursiveExpression('numbers', $query, ['number'])
    ->get();

INSERT/UPDATE/DELETE 查询

您可以在 INSERTUPDATEDELETE 查询中使用公用表表达式

DB::table('profiles')
    ->withExpression('u', DB::table('users')->select('id', 'name'))
    ->insertUsing(['user_id', 'name'], DB::table('u'));
DB::table('profiles')
    ->withExpression('u', DB::table('users'))
    ->join('u', 'u.id', '=', 'profiles.user_id')
    ->update(['profiles.name' => DB::raw('u.name')]);
DB::table('profiles')
    ->withExpression('u', DB::table('users')->where('active', false))
    ->whereIn('user_id', DB::table('u')->select('id'))
    ->delete();

Eloquent

您可以在 Eloquent 查询中使用公用表表达式

$query = User::whereNull('parent_id')
    ->unionAll(
        User::select('users.*')
            ->join('tree', 'tree.id', '=', 'users.parent_id')
    );

$tree = User::from('tree')
    ->withRecursiveExpression('tree', $query)
    ->get();

递归关系

如果您想实现递归关系,可以使用此包:[staudenmeir/laravel-adjacency-list](https://github.com/staudenmeir/laravel-adjacency-list)