当前位置: 首页 > 软件库 > 开发工具 > PHP开发工具 >

laravel-schemaless-attributes

Add schemaless attributes to Eloquent models
授权协议 MIT License
开发语言 PHP
所属分类 开发工具、 PHP开发工具
软件类型 开源软件
地区 不详
投 递 者 逄俊力
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Add schemaless attributes to Eloquent models

Latest Version on PackagistGitHub Workflow StatusTotal Downloads

Wouldn't it be cool if you could have a bit of the spirit of NoSQL available in Eloquent? This package does just that. It provides a trait that when applied on a model, allows you to store arbitrary values in a single JSON column.

Here are a few examples. We're using the extra_attributes column here, but you can name it whatever you want.

// add and retrieve an attribute
$yourModel->extra_attributes->name = 'value';
$yourModel->extra_attributes->name; // returns 'value'

// you can also use the array approach
$yourModel->extra_attributes['name'] = 'value';
$yourModel->extra_attributes['name'] // returns 'value'

// setting multiple values in one go
$yourModel->extra_attributes = [
   'rey' => ['side' => 'light'],
   'snoke' => ['side' => 'dark']
];

// setting/updating multiple values in one go via set()
$yourModel->extra_attributes->set([
   'han' => ['side' => 'light'],
   'snoke' => ['side' => 'dark']
]);

// retrieving values using dot notation
$yourModel->extra_attributes->get('rey.side'); // returns 'light'

// retrieve default value when attribute is not exists
$yourModel->extra_attributes->get('non_existing', 'default'); // returns 'default'

// it has a modelScope to retrieve all models with the given schemaless attributes
$yourModel->withSchemalessAttributes(['name' => 'value', 'name2' => 'value2'])->get();

// delete key & value
$yourModel->extra_attributes->forget('key');

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Requirements

This package requires a database with support for json columns like MySQL 5.7 or higher.

Installation

For Laravel versions 6 & 7 or PHP 7, use version 1.x of this package.

You can install the package via composer:

composer require spatie/laravel-schemaless-attributes

The schemaless attributes will be stored in a json column on the table of your model. Let's add that column and prepare the model.

Adding the column where the schemaless attributes will be stored

Add a migration for all models where you want to add schemaless attributes to. You should use schemalessAttributes method on Blueprint to add a column. The argument you give to schemalessAttributes is the column name that will be added. You can use any name you'd like. You're also free to add as many schemaless attribute columns to your table as you want. In all examples of this readme we'll use a single column named extra_attributes.

Schema::table('your_models', function (Blueprint $table) {
    $table->schemalessAttributes('extra_attributes');
});

Preparing the model

In order to work with the schemaless attributes you'll need to add a custom cast and a scope on your model. Here's an example of what you need to add if you've chosen extra_attributes as your column name.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;

class TestModel extends Model
{
    // ...

    public $casts = [
        'extra_attributes' => SchemalessAttributes::class,
    ];

    public function scopeWithExtraAttributes(): Builder
    {
        return $this->extra_attributes->modelScope();
    }

    // ...
}

If you need support for multiple schemaless columns on a single model, you should use SchemalessAttributesTrait trait. Here's an example of what you need to add if you've chosen extra_attributes, other_extra_attributes as your column names.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Spatie\SchemalessAttributes\SchemalessAttributes;
use Spatie\SchemalessAttributes\SchemalessAttributesTrait;

class TestModel extends Model
{
    use SchemalessAttributesTrait;

    // ...
    
    /**
     * @var array
     */
    protected $schemalessAttributes = [
        'extra_attributes',
        'other_extra_attributes',
    ];

    public function scopeWithExtraAttributes(): Builder
    {
        return $this->extra_attributes->modelScope();
    }
    
    public function scopeWithOtherExtraAttributes(): Builder
    {
        return $this->other_extra_attributes->modelScope();
    }

    // ...
}

If you want to reuse this behaviour across multiple models you could opt to put the function in a trait of your own. Here's what that trait could look like:

namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;

trait HasSchemalessAttributes
{
    public function initializeHasSchemalessAttributes()
    {
        $this->casts['extra_attributes'] = SchemalessAttributes::class;
    }
    
    public function scopeWithExtraAttributes(): Builder
    {
        return $this->extra_attributes->modelScope();
    }
}

Usage

Getting and setting schemaless attributes

This is the easiest way to get and set schemaless attributes:

$yourModel->extra_attributes->name = 'value';

$yourModel->extra_attributes->name; // Returns 'value'

Alternatively you can use an array approach:

$yourModel->extra_attributes['name'] = 'value';

$yourModel->extra_attributes['name']; // Returns 'value'

You can replace all existing schemaless attributes by assigning an array to it.

// All existing schemaless attributes will be replaced
$yourModel->extra_attributes = ['name' => 'value'];
$yourModel->extra_attributes->all(); // Returns ['name' => 'value']

You can also opt to use get and set. The methods have support for dot notation.

$yourModel->extra_attributes = [
   'rey' => ['side' => 'light'],
   'snoke' => ['side' => 'dark'],
];
$yourModel->extra_attributes->set('rey.side', 'dark');

$yourModel->extra_attributes->get('rey.side'); // Returns 'dark

You can also pass a default value to the get method.

$yourModel->extra_attributes->get('non_existing', 'default'); // Returns 'default'

Persisting schemaless attributes

To persist schemaless attributes you should, just like you do for normal attributes, call save() on the model.

$yourModel->save(); // Persists both normal and schemaless attributes

Retrieving models with specific schemaless attributes

Here's how you can use the provided modelScope.

// Returns all models that have all the given schemaless attributes
$yourModel->withExtraAttributes(['name' => 'value', 'name2' => 'value2'])->get();

If you only want to search on a single custom attribute, you can use the modelScope like this

// returns all models that have a schemaless attribute `name` set to `value`
$yourModel->withExtraAttributes('name', 'value')->get();

If you only want to search on a nested custom attribute, you can use the modelScope like this

// returns all models that have a schemaless nested attribute `han.side` set to `light`
$yourModel->withExtraAttributes('han->side', 'light')->get();

Testing

First create a MySQL database named laravel_schemaless_attributes. After that you can run the tests with:

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

 相关资料
  • Laravel 是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。 功能特点 1、语法更富有表现力 你知道下面这行代码里 “true” 代表什么意思么? $uri = Uri::create(‘some/uri’, array(), array(), tr

  • 我需要空间/Laravel权限的帮助。当我试图分配它给我错误哎呀,看起来像出了问题。 错误 Connection.php第761行中的QueryExcema:SQLSTATE[23000]:完整性约束冲突:1048列role_id不能为空(SQL:插入到(,)值(9,))

  • Laravel 作为现在最流行的 PHP 框架,其中的知识较多,所以单独拿出来写一篇。 简述 Laravel 的生命周期 Laravel 采用了单一入口模式,应用的所有请求入口都是 public/index.php 文件。 注册类文件自动加载器 : Laravel通过 composer 进行依赖管理,无需开发者手动导入各种类文件,而由自动加载器自行导入。 创建服务容器:从 bootstrap/ap

  • 简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer

  • 简介 Laravel 致力于让整个 PHP 开发体验变得愉快, 包括你的本地开发环境。 Vagrant 提供了一种简单,优雅的方式来管理和配置虚拟机。 Laravel Homestead 是一个官方预封装的 Vagrant box,它为你提供了一个完美的开发环境,而无需在本地机器安装 PHP 、Web 服务器和其他服务器软件。不用担心会搞乱你的操作系统!Vagrant boxes 是一次性的。如果

  • WebStack-Laravel 一个开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己的网址导航。 部署 克隆代码: git clone https://github.com/hui-ho/WebStack-Laravel.git 安装依赖: composer installphp artisan key:generate 编辑配置: cp .env.example .env ...D