gertjanroke / laravel-db-model
围绕 DB 类的模型包装,以保持代码整洁
1.0.0
2021-09-22 20:02 UTC
Requires
- php: ^7.4|^8.0
- illuminate/collections: ^8.37
- illuminate/database: ^8.37
- illuminate/support: ^8.37
- spatie/laravel-package-tools: ^1.4.3
Requires (Dev)
- nunomaduro/collision: ^5.3
- orchestra/testbench: ^6.15
- pestphp/pest: ^1.18
- pestphp/pest-plugin-laravel: ^1.1
README
围绕 DB 类的模型包装,以保持代码整洁。
安装
您可以通过 composer 安装此包
composer require gertjanroke/laravel-db-model
用法
<?php namespace App\Models; use GertjanRoke\LaravelDbModel\DBModel; class Post extends DBModel { // public $table = 'posts'; // public $connection = 'mysql'; }
如果没有提供表名,它将根据类名猜测它,就像 Eloquent 模型那样。
对于连接也是如此,如果没有设置,它将使用默认连接。
如何扩展自定义作用域
基本上和 Eloquent 模型一样,您需要将方法前缀为 scope
... class Post extends DBModel { public function scopeActive() { $this->db->where('active', true); return $this; } }
一些示例
您可以轻松创建基本 where 查询或更复杂查询的简短函数,这样您就可以在代码库中的一个位置而不是每个地方找到它。
<?php namespace App\Models; use App\Models\Comment; use GertjanRoke\LaravelDbModel\DBModel; class Post extends DBModel { public function scopeActive(): self { $this->db->where('active', true); return $this; } public function scopeWithLatestComment(): self { $postTable = $this->getTable(); $commentTable = (new Comment())->getTable(); $this->db->join($commentTable, "{$commentTable}.post_id", '=', "{$postTable}.id") ->addSelect("{$commentTable}.body"); return $this; } } // Inside your controller $post = Post::active()->withLatestComment()->latest()->first(); // Keep in mind the order of calling methods doesn't matter as long as the method before returned the builder instance. // Like this example will return the same result as the query above. $post = Post::active()->latest()->withLatestComment()->first();
测试
composer test
变更日志
有关最近更改的更多信息,请参阅 CHANGELOG
贡献
有关详细信息,请参阅 CONTRIBUTING
安全漏洞
有关报告安全漏洞的详细信息,请查看 我们的安全策略
鸣谢
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件