leemason / metable
Laravel Eloquent Metable 包专门设计用于将元信息关联到 Eloquent 模型。
Requires
- illuminate/database: 5.1.*
- illuminate/support: 5.1.*
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-14 18:26:04 UTC
README
Laravel Eloquent Metable 包专门设计用于将 "meta" 信息关联到 Eloquent 模型。
安装
只需通过 composer.json 在您的 Laravel 安装中添加新包
composer require leemason/metable
然后执行 composer update
兼容性
Metable 包是针对 Laravel 5.1 开发的,我认为它也应该与 5.0 或甚至 4 版本兼容,但仅针对 5.1 进行了测试。
简介
这个包有众多用例,最显著的是用户模型,您可能需要分配多种不同的配置信息。
理想情况下,您会始终在模型表中提供唯一的列来处理所有数据,但在更动态的应用程序中,这可能不是可行的选项。
这正是 "meta" 信息发挥作用的地方。
此包提供了将任何类型的数据关联到模型的方法,从整数、浮点数、布尔值、数组到集合和对象。
它不仅使分配这些数据变得简单,而且还格式化数据库和返回使用时的数据。
例如,用户可能需要多个社交链接,使用此包,您可以创建一个包含数据的集合,立即将其保存为集合(以 JSON 编码字符串的形式保存)。然后,在将来检索它时,它将被转换回集合。
"meta" 信息以关联的 Eloquent 模型和简单的键/值访问方式保存。
在后台,元模型还保存了用于返回的 "type" 值。
该包包含 2 个特质,提供所需的所有功能,以及一些帮助器,使管理信息更加容易。
Metable
特质用于将 Eloquent 模型转换为元模型,并提供格式化元值的所有后台逻辑。
主功能通过 HasMeta
特质访问。
以下是一些示例(更多信息请查看文档文件夹)。
class User extends Eloquent{ use LeeMason\Metable\HasMeta; protected $metaModel = 'UserMeta'; } class UserMeta extends LeeMason\Metable\MetaModel{ // By extending the MetaModel we dont have to set the $fillable or $casts properties! // Or you can just use the trait } $user = new User(); // uses Eloquent firstOrNew to either create or fetch/update the field by "key" $user->addMeta('key', 'value'); // simple wrapper around addMeta for readability $user->updateMeta('collection', new Collection(['collection', 'items'])); // need to save lots of data? not a problem $user->fillMeta([ 'meta1' => true, 'meta2' => 200, 'meta3' => [1,2,3], .... ]); // deleting is easy too $user->deleteMeta('meta2'); // this will return a Collection object $collection = $user->getMeta('collection'); // and of course, the meta data are related models so can be accessed, or set as such too $user->meta(); //or $user->meta //and $meta = new UserMeta(); $meta->key = 'thekey'; $meta->value = 'some value'; $user->meta()->save($meta);