roy404/eloquent

Eloquent 是默认的 ORM(对象关系映射)。它提供了一个简单的 ActiveRecord 实现,用于与数据库交互。使用 Eloquent,您可以定义数据库模型为类,并通过这些模型与数据库交互,而不是编写原始的 SQL 查询。

1.0.1 2024-02-19 12:05 UTC

This package is auto-updated.

Last update: 2024-09-19 13:36:11 UTC


README

使用 Composer 安装包

composer require roy404/eloquent

文档

Eloquent 类是一个数据库查询构建器,提供了一个流畅的接口来创建 SQL 查询。

方法

  • table(): 为查询设置表。
  • select(): 向选择子句添加列。
  • where(): 向查询添加 WHERE 子句。
  • orWhere(): 向查询添加 OR WHERE 子句。
  • orderBy(): 向查询添加排序子句。
  • offset(): 向查询添加偏移量子句。
  • limit(): 向查询添加限制子句。
  • create(): 在数据库中创建新记录。
  • replace(): 替换数据库中的记录。

模型

Model 类扩展了 Eloquent,并为与模型对应的数据库表提供了额外的交互方法。

  • all(): array: 从数据库表中检索所有记录。
  • create(array $binds): int: 在数据库表中创建新记录。
  • replace(array $binds): int: 在数据库表中替换记录。
  • find(int $id): array: 通过主键检索记录。
  • select(...$columns): Eloquent: 从数据库表中选择特定列。
  • where(string $column, mixed $operator_or_value, mixed $value = self::DEFAULT_VALUE): Eloquent: 向查询添加 WHERE 子句。

返回数据

然而,这些函数尚未完全实现;您需要自行完成它们。

  • lastID(): int: 返回数据库中最后插入的 ID。
  • fetch(): array: 将结果集中的所有行作为数组数组检索。
  • col(): array: 将结果集中所有行的第一列作为数组检索。
  • field(): mixed: 从结果集的第一行中检索单个字段值。
  • row(): array: 将结果集中的第一行作为关联数组检索。
  • count(): int: 返回受最后一个 SQL 语句影响的行数。

示例用法

// Define the User class
class User extends Model
{
    protected string $primary_key = 'id';
    protected array $fillable = ['name'];
}

// Create a new user
$userId = User::create([
    'name' => 'Robroy'
]);

// Retrieve a user by ID
$user = User::find($userId);

// Update a user's record
User::where( 'name', 'Robroy' )->update(['name' => 'Robert']);

// Delete a user's record
User::where( 'name', 'Robert' )->delete();

// Another Example
$user = User::select( 'name', 'email', 'contact' )
    ->where( 'name', '<>', 'robot' )
    ->where( 'email', 'canales.robroy123@gmail.com' )
    ->where( function( \Illuminate\Databases\Eloquent $group ) {
        $group->where( 'contact', '+63 917 130 4494' )
              ->orWhere( 'contact', '216-2944' )
    })
    ->limit( 1 )
    ->row();

// Another Example [2]
DB::table( 'user' )->select( 'name' )->where( 'id', $userId )->field();    

您需要更改以下函数的逻辑

Illuminate\Databases\DB::run() - 我们建议您创建自己的类,在该类中使用 Return Data list 中提供的操作执行查询。