dhcmega/laravel-meta 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

dhcmega/laravel-meta

Composer 安装命令:

composer require dhcmega/laravel-meta

包简介

Fork from kodeine/laravel-meta. Fluent Meta Data for Eloquent Models, as if it is a property on your model.

README 文档

README

Laravel Source Build Status License

Metable Trait adds the ability to access meta data as if it is a property on your model. Metable is Fluent, just like using an eloquent model attribute you can set or unset metas. Follow along the documentation to find out more.

Installation

Composer

Add this to your composer.json file, in the require object:

"dhcmega/laravel-meta": "master"

After that, run composer install to install the package.

Migration Table Schema

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
    Schema::create('posts_meta', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('post_id')->unsigned()->index();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

        $table->string('type')->default('null');

        $table->string('key')->index();
        $table->text('value')->nullable();

        $table->timestamps();
    });
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
    Schema::drop('posts_meta');
}

Configuration

Model Setup

Next, add the Metable trait to each of your metable model definition:

use Dhcmega\Metable\Metable;

class Post extends Eloquent
{
    use Metable;
}

Metable Trait will automatically set the meta table based on your model name. Default meta table name would be, model_meta. In case you need to define your own meta table name, you can specify in model:

class Post extends Eloquent
{
    protected $metaTable = 'posts_meta'; //optional.
}

Default Model Attribute values

Additionally, you can set default values by setting an array called $defaultMetaValues on the model. Setting default has two side-effects:

  1. If a meta attribute does not exist, the default value will be returned instead of null.

  2. if you attempt to set a meta attribute to the default value, the row in the meta table will be removed, which will cause the default value to be returned, as per rule 1.

This is be the desired and expected functionality for most projects, but be aware that you may need to reimplement default functionality with your own custom accessors and mutators if this functionality does not fit your needs.

This functionality is most suited for meta entries that note exceptions to rules. For example: employees sick out of office (default value: in office), nodes taken down for maintance (default value: node up), etc. This means the table doesn't need to store data on every entry which is in the expected state, only those rows in the exceptional state, and allows the rows to have a default state upon creation without needing to add code to write it.

   public $defaultMetaValues = [
      'is_user_home_sick' => false,
   ];

Gotcha

When you extend a model and still want to use the same meta table you must override getMetaKeyName function.

class Post extends Eloquent
{

}

class Slideshow extends Post
{
    protected function getMetaKeyName()
    {
        return 'post_id' // The parent foreign key
    }   
}

Working With Meta

Setting Content Meta

To set a meta value on an existing piece of content or create a new data:

Fluent way, You can set meta flawlessly as you do on your regular eloquent models. Metable checks if attribute belongs to model, if not it will access meta model to append or set a new meta.

$post = Post::find(1);
$post->name = 'hello world'; // model attribute
$post->content = 'some content goes here'; // meta data attribute
$post->save(); // save attributes to respective tables

Or

$post = Post::find(1);
$post->name = 'hello world'; // model attribute
$post->setMeta('content', 'Some content here');
$post->save();

Or set multiple metas at once:

...
$post->setMeta([
    'content' => 'Some content here',
    'views' => 1,
]);
$post->save();

Or set multiple metas and columns at once:

...
$post->setAttributes([
    'name' => 'hello world'; // model attribute
    'content' => 'Some content here',
    'views' => 1,
]);
$post->save();

Note: If a piece of content already has a meta the existing value will be updated.

Unsetting Content Meta

Similarly, you may unset meta from an existing piece of content:

Fluent way to unset.

$post = Post::find(1);
$post->name // model attribute
unset($post->content) // delete meta on save
$post->save();

Or

$post->unsetMeta('content');
$post->save();

Or unset multiple metas at once:

$post->unsetMeta('content,views');
// or
$post->unsetMeta('content|views');
// or
$post->unsetMeta('content', 'views');
// or array
$post->unsetMeta(['content', 'views']);

$post->save();

Note: The system will not throw an error if the content does not have the requested meta.

Checking for Metas

To see if a piece of content has a meta:

Fluent way, Metable is clever enough to understand $post->content is an attribute of meta.

if (isset($post->content)) {

}

Retrieving Meta

To retrieve a meta value on a piece of content, use the getMeta method:

Fluent way, You can access meta data as if it is a property on your model. Just like you do on your regular eloquent models.

$post = Post::find(1);
dump($post->name);
dump($post->content); // will access meta.

Or

$post = $post->getMeta('content');

Or specify a default value, if not set:

$post = $post->getMeta('content', 'Something');

You may also retrieve more than one meta at a time and get an illuminate collection:

// using comma or pipe
$post = $post->getMeta('content|views');
// or an array
$post = $post->getMeta(['content', 'views']);

Retrieving All Metas

To fetch all metas associated with a piece of content, use the getMeta without any params

$metas = $post->getMeta();

Retrieving an Array of All Metas

To fetch all metas associated with a piece of content and return them as an array, use the toArray method:

$metas = $post->getMeta()->toArray();

Meta Table Join

When you need to filter your model based on the meta data , you can use meta scope in Eloquent Query Builder.

$post = Post::meta()
    ->where(function($query){
          $query->where('posts_meta.key', '=', 'revision')
                ->where('posts_meta.value', '=', 'draft');
    })

Eager Loading

When you need to retrive multiple results from your model, you can eager load metas

$post = Post::with(['metas'])->get();

Prevent metas attribute from being populated

When you convert a model to an array (or json) and you don't need all meta fields, you can create a model's property to prevent metas from being added to the resulting array. You can also use it on eloquent relations.

/* Post model */
public $hideMeta = true; // Do not add metas to array

dhcmega/laravel-meta 适用场景与选型建议

dhcmega/laravel-meta 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 10 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「metadata」 「data」 「model」 「laravel」 「meta」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 dhcmega/laravel-meta 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 dhcmega/laravel-meta 我们能提供哪些服务?
定制开发 / 二次开发

基于 dhcmega/laravel-meta 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 5
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 90
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-10-06