zablockibros / laravel-schemaless
创建无模式模型
dev-master
2019-03-04 20:00 UTC
Requires
- php: ^7.1.3
- doctrine/dbal: ^2.9
- illuminate/config: ~5.7.0
- illuminate/console: ~5.7.0
- illuminate/database: ~5.7.0
- illuminate/support: ~5.7.0
Requires (Dev)
- fzaninotto/faker: ^1.4
- mockery/mockery: ^1.0
- phpunit/phpunit: ~7.0
This package is auto-updated.
Last update: 2024-09-05 19:33:52 UTC
README
使用模型创建原型,无需创建迁移或更改数据库模式。
为什么?
在快速原型化API或Web应用时,您将不断添加和修改模型的表列和关系。使用Schemaless,您可以简单地创建模型并扩展ZablockiBros\Models\Item
模型,并定义$extraAttributes
。创建记录、设置属性、填充记录,所有这些都可以像在Laravel中那样进行。
安装
要求:此包需要PHP 7.1.3或更高版本以及Laravel 5.7
-
通过Composer安装此包
$ composer require zablockibros/laravel-schemaless
包将自动注册其服务提供者。
-
发布包
php artisan vendor:publish --provider="ZablockiBros\Schemaless\SchemalessServiceProvider"
-
运行迁移
php artisan migrate
配置您的模型
您可以使用schemaless属性和关系,使用您自己的表或迁移提供的items
表和基本Item
模型类。
使用Item基础模型
-
创建您的模型
php artisan make:model Models/YourModel
-
扩展
ZablockiBros\Models\Item
类class YourModel extends \ZablockiBros\Models\Item
-
定义您的schemaless属性
<?php namespace App\Models; use ZablockiBros\Schemaless\Models\Item; class YourModel extends Item { /** * @var array */ protected $extraAttributes = [ 'name' => null, // attribute 'name' with default null 'options' => null, 'qty' => 0, ]; /** * @var array */ protected $casts = [ 'options' => 'array', ]; }
使用您自己的表
您可以使用schemaless属性、关系和表使用自己的现有表和模型。
Schemaless提供了三个核心特质
HasSchemalessAttributes
、HasSchemalessRelationships
和HasSchemalessTable
。
设置您的模型
- 创建您的表和模型(如果您不使用
HasSchemalessTable
,则只需创建新表)。 - 将所需的特质添加到您的模型中。
- 如上所述配置您的
$extraAttributes
和关系。
注意事项
- 如果您使用
HasSchemalessAttributes
,请确保您的表有一个名为columns
的json
类型列。如果您想将其命名为其他名称,请使用以下方法在您的模型中覆盖列名/** * @return string */ protected function getExtraAttributesColumnName() { return 'my_columns'; }
- 如果您使用
HasSchemalessRelations
,请确保您的表有一个名为itemable
的morphs
列(或您自己的名称)。如果您使用不同的morph名称,请覆盖以下在您的模型中/** * @return string */ public function getItemMorphColumnName() { return 'itemable'; }
- 如果您使用
HasSchemalessTable
特质,则必须为您的schemaless模型使用items
表。
访问属性
您可以通过与Eloquent模型相同的方式访问属性
$yourModel->name; // 'test'
保存属性
同样以相同的方式保存属性
YourModel::create([ 'name' => 'test', ]); YourModel::firstOrNew([ 'name' => 'test', ]); $yourModel->fill([ 'name' => 'test', ]); YourModel::where(...) ->update([ 'name' => 'test', ]); $yourModel->name = 'test'; $yourModel->save();
关系
进行中
注意:查询属性
Schemaless属性需要在模型表的json
列中查询(在模型扩展Item
的情况下为items
)。
YourModel::where('columns->name', 'test');
版权和许可
版权(c)2019 Justin Zablocki