codingpaws/laravel-findby

在 Laravel 模型查询中使用类似 Ruby 的 findBy。

2.3 2022-07-30 15:54 UTC

This package is auto-updated.

Last update: 2024-09-29 05:56:39 UTC


README

codingpaws/laravel-findby 库允许你在 Laravel 的 Eloquent 查询中使用现代 PHP 8.0 的 命名参数,类似于 Ruby 的 Active Record find_by

class User extends Model
{
    use CodingPaws\FindBy\FindBy;
}

User::findBy(
    first_name: 'Jane',
    role_id: 5,
    is_admin: false,
)->get();

它还引入了一个 findByNot 方法,它是等于不等(!=)的简写。

Book::findByNot(
    genre: 'SciFi',
    legth: 'long',
)->findBy(genre: 'Drama', author: 'Dürrenmatt')->get();

该项目仍处于早期阶段。该 技术解决方案 是建立在 Laravel 现有的查询构建器之上的。在添加新功能的同时,我们需要确保现有的功能仍然正常工作。

安装

composer require kevslashnull/futuristic-eloquent-builder

未来的 Eloquent 构建器是按模型可选的。要对给定的模型执行具有命名参数的查询,请在其类中使用特性(use FindBy)。

支持的方法

您可以在模型上使用这些方法(例如 Book::findBy)以及该模型的构建器上(例如 Book::where('id', 3)->findBy)。

  • findBy,类似于本机的 where
  • findByNot,类似于本机的 where 但相反(使用 != 而不是 =
  • orFindBy,类似于本机的 orWhere
  • orFindByNot,类似于本机的 orWhere 但相反(使用 != 而不是 =

所有方法都支持使用数组作为值。例如,

Book::findBy(
    genre: ['SciFi', 'Adventure', 'Drama'],
)->get();

查询所有 genre 列为科幻、冒险或剧情的书籍。

技术背景

大多数魔法发生在 NamedBuilder 类中。它通过 findByfindByNot 方法扩展了 Eloquent 的 Builder 类。通过重写 where 方法并始终返回一个 NamedBuilder 实例,可以实现 wherefindBy 的链式调用。

库的 1.0 版本允许在 where 查询中使用命名参数,但它最终变得不可能,因为。

实际上,

User::findBy(first_name: 'John', last_name: 'Doe', gender: 'male');

翻译成

User::where('first_name', 'John')->where('last_name', 'Doe'->where('gender', 'male');

每个人都可以贡献

该项目采用 MIT 许可。每个人都可以贡献。 ❤️