loilo/contao-illuminate-database-bundle

在 Contao 中使用 Laravel 的 Illuminate 数据库抽象层

1.1.0 2019-08-19 12:49 UTC

This package is auto-updated.

Last update: 2024-09-24 07:27:15 UTC


README

Tests Version on packagist.org

在 Contao 中使用 Laravel 的 Illuminate Database 抽象层,并支持 Contao 模型。

安装

composer require loilo/contao-illuminate-database-bundle

用法

入门指南

获取 db() 辅助函数

use function Loilo\ContaoIlluminateDatabaseBundle\Database\db;

调用 db() 函数将创建一个新的 Laravel 查询构建器 实例。

基本查询

这是我们获取 Contao 安装中最早的管理员 ID 和名称的方式

$row = db()
  ->select('id', 'name')
  ->from('user')
  ->where('admin', '1')
  ->orderBy('dateAdded')
  ->first();

注意,tl_ 前缀会自动添加到表名前,所以我们实际上从 tl_user 读取。

上面的只是一个非常基础的例子。要了解此 API 的可能性,请参考 Laravel 文档

获取模型

除了 Laravel 内置的方法之外,此包的查询构建器还公开了一个额外的 asModel() 方法。

在查询构建器链中使用它将指示 get()first()find()cursor() 方法返回 Contao 模型而不是纯数据库记录。

以下面面的例子来解释这一点

$user = db()
  ->from('user')
  ->asModel() // <- notice this line
  ->where('admin', '1')
  ->orderBy('dateAdded')
  ->first();

// $user will be an instance of \UserModel

自定义连接

db() 函数接受一个可选参数,该参数可以覆盖传递给 Laravel 连接管理器的默认连接配置 的键

// Set an empty prefix to use the "tl_user" table
db([ 'prefix' => '' ])->from('tl_user')->first();