sukohi / metaphor
一款允许您管理元数据的 Laravel 扩展包。
3.0.1
2019-05-06 09:28 UTC
Requires
- laravel/framework: ~5.8.13
README
一款允许您管理元数据的 Laravel 扩展包。本扩展包在 Laravel 5.8 下维护。
安装
运行以下命令。
composer require sukohi/metaphor:3.*
准备
1. 特性
在您的模型中设置 MetaphorTrait
,如下所示。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Sukohi\Metaphor\MetaphorTrait;
class Item extends Model
{
use MetaphorTrait;
}
2. 迁移
只需运行迁移命令。
注意: 您无需自行创建迁移,因为本扩展包已包含。
php artisan migrate
就这样!
使用方法
保存
$item = \App\Item::find(1);
$item->meta->key_1 = 300;
$item->meta->key_2 = 'yyy';
$item->meta->key_3 = ['item_1x', 'item_2', 'item_3'];
$item->meta->key_4 = null;
$item->meta->save();
注意: $item->meta
是 Laravel 扩展的 Collection。
所以您可以使用所有常规方法。
删除
$item->meta->delete($key);
// or
$item->meta->deleteAll();
检查元数据值是否存在
if($item->meta->has($key)) {
// has it!
}
关于追加
如果您想将元数据包含在模型数据中,请将 meta
设置为 $appends
。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Sukohi\Metaphor\MetaphorTrait;
class Item extends Model
{
use MetaphorTrait;
protected $appends = ['meta']; // <- here
}
条件查询
1. whereMeta
\App\Item::whereMeta('price', '500')->get();
\App\Item::whereMeta('price', 'LIKE', '%50%')->get();
\App\Item::orWhereMeta('price', '500')->get();
\App\Item::orWhereMeta('price', 'LIKE', '%50%')->get();
2. whereMetaIn
\App\Item::whereMetaIn('price', [300, 500])->get();
\App\Item::orWhereMetaIn('price', [300, 500])->get();
3. whereMetaNotIn
\App\Item::whereMetaNotIn('price', [300, 500])->get();
\App\Item::orWhereMetaNotIn('price', [300, 500])->get();
4. whereMetaNull
\App\Item::whereMetaNull('price')->get();
\App\Item::orWhereMetaNull('price')->get();
5. whereMetaNotNull
\App\Item::whereMetaNotNull('price')->get();
\App\Item::orWhereMetaNotNull('price')->get();
OrderByMeta
\App\Item::orderByMeta($key', 'asc')->get();
\App\Item::orderByMeta($key', 'desc')->get();
注意: 此方法使用 SQL 中的 FIELD(value, val1, val2, val3, ...)
函数。
这意味着如果您的数据库系统没有此函数,则此功能将 不可用。不过 MySQL 有。
许可证
本扩展包遵循 MIT 许可证。
版权所有 2019 Sukohi Kuhoh