stelianandrei/eloquent-custom-fields

为你的 Eloquent 模型添加任何额外的字段

v0.1.0 2020-10-30 15:31 UTC

This package is auto-updated.

Last update: 2024-09-29 05:48:59 UTC


README

此包提供了将任意字段附加到 Eloquent 模型的基本方法。自定义字段只是与你的模型通过 MorphToMany 关系相关联的 Eloquent 模型的集合。

安装

此包可以通过 Composer 安装。

composer require stelianandrei/eloquent-custom-fields

确保发布所需的迁移

php artisan vendor:publish --provider="StelianAndrei\EloquentCustomFields\ServiceProvider" --tag="migrations"

可选,发布配置

php artisan vendor:publish --provider="StelianAndrei\EloquentCustomFields\ServiceProvider" --tag="config"

CustomField 模型

模型非常简单,它只有两个属性

  • label - (必填) 主要用于以可读形式识别 CustomField
  • type - (可选) 自定义字段代表的含义。这可以用来确定如何处理该字段(例如,“文本”,“电子邮件”,“多行文本”)或其他作为数据操作提示的内容(例如,“json”,“货币”,“经纬度”)。

如果你需要为此模型添加额外功能,只需创建一个新的模型,扩展 StelianAndrei\EloquentCustomFields\CustomField 类,并在配置文件中更新 field_class 的值(确保首先发布,见上文)。

使用方法

为了使你的模型能够使用此功能,你需要使用 HasCustomFields 特性

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use StelianAndrei\EloquentCustomFields\HasCustomFields;

class MyModel extends Model
{
    use HasCustomFields;

    //
}

创建字段就像创建任何其他模型一样,然后将它关联到你的模型,并使用所需的值。

use StelianAndrei\EloquentCustomFields\CustomField;

$firstName = CustomField::new(['label' => 'First Name']);
$lastName = CustomField::new(['label' => 'Last Name']);

$myModel->customFields()->attach($firstName, ['value' => 'John']);
$myModel->customFields()->attach($lastName, ['value' => 'Doe']);

创建或删除模型之间关系的任何其他方法也应正常工作。