freshwork/metable

为您的 eloquent 模型添加元数据

0.1.5 2016-10-07 00:46 UTC

This package is not auto-updated.

Last update: 2024-09-23 04:57:45 UTC


README

安装

composer require freshwork/metable

Freshwork\Metable\MetableServiceProvider 添加到您的 app.php 配置文件中

'providers' => [
    ...
    Freshwork\Metable\MetableServiceProvider::class
]

运行 laravel 迁移以在数据库上安装 metas

php artisan migrate

用法

Freshwork\Metable\Traits\Metable 特性添加到您的 eloquent 模型中

namespace App;

use Freshwork\Metable\Traits\Metable;

class Post extends Model {
    use Metable;
    ...
}

添加元数据

目前,addMeta 立即执行一个 SQL 查询以保存。

$post->addMeta('key', 'value');
$post->addMeta('foo', ['bar', 'baz']); //saved as json
$post->addMeta('third', 'value1');
$post->addMeta('third', 'value2');

获取元数据

请记住,您可以针对相同的键添加多个元数据,因此默认情况下,getMeta() 返回一个数组,即使只有一个值。您可以使用 single 参数直接获取第一个值

getMeta($key, $single = false, $cacheAll = true)

预加载:如果将 $cacheAll 设置为 true,当您获取元数据时,您将检索模型的全部元数据,因此下一次 getMeta 调用不会触及数据库。

$post->getMeta('key'); // ['value']
$post->getMeta('foo'); // [ ['bar', 'baz'] ]
$post->getMeta('third'); // [ 'value1', 'values2' ]

//If you want to get the first element of the array
$post->getMeta('key', true); // 'value'
$post->getMeta('foo', true); // ['bar', 'baz']
$post->getMeta('third', true); // 'value1'

获取所有元数据

//Load $post->metadata variable
$post->loadMeta();

//Then you can 
dd($post->metadata->key); //['value']

删除元数据

//Load $post->metadata variable
$post->removeMeta('key'); //remove all the ocurrences of metas with that key in the current model