079. 为你的 Laravel 模型加上类 NoSQL 属性 ——laravel-schemaless-attributes

为你的 Laravel 模型加上 Schemaless 属性——spatie/laravel-schemaless-attributes

Laravel 提供了一个功能 修改器《Laravel 5.7 中文文档》 可以将一个数组序列化的转换为 Json 然后保存在数据库中,这样我们只需要直接操作数组就可以了,省去了关系型数据库字段的定义。

今天要了解的这个扩展包 github.com/spatie/laravel-schemale... ,是在这个功能之上的补充,让这个功能更加的好用,这节课我们在一个全新的 5.8 的项目中,测试一下。

注意这个扩展包要求数据库支持 Json,Mysql 的版本需要大于 5.7

安装

$ git checkout -b schemaless-attriutes
$ composer require spatie/laravel-schemaless-attributes

file

使用

创建 migration ,添加一个字段。

$ php artisan make:migration add_extra_attributes_to_users_table

_add_extra_attributes_to_users_table.php

.
.
.
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->schemalessAttributes('extra_attributes');
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('extra_attributes');
        });
    }
.
.
.

执行 migrate,查看数据库,注意到添加了 extra_attributes 字段,类型为 Json。

file

接着需要配置一下 User 模型,文档中有提示,为了更好的复用,可以先创建一个 Trait。

这是个演示项目,暂时就放在 app 目录中。

$ touch app/HasSchemalessAttributes.php

app/HasSchemalessAttributes.php

<?php

namespace App;

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

trait HasSchemalessAttributes
{
    public function getExtraAttributesAttribute(): SchemalessAttributes
    {
       return SchemalessAttributes::createForModel($this, 'extra_attributes');
    }

    public function scopeWithExtraAttributes(): Builder
    {
        return SchemalessAttributes::scopeWithSchemalessAttributes('extra_attributes');
    }
}

app/User.php

    use HasSchemalessAttributes;

    protected $casts = [
        'email_verified_at' => 'datetime',
        'extra_attributes' => 'array',
    ];

这样基础的配置就完成了,User 模型额外的属性都可以保存在 extra_attributes 中。

赋值查询

基本的用法同我们不使用扩展包的时候相同,直接操作数据库可以了,但是有了扩展包,我们可以使用的更加方便,例如赋值:

打开 Tinker 测试一下。

$user = User::first();
$user->extra_attributes->company = 'foobar company';
$user->extra_attributes->position = 'php';
$user->save();

file

还可以赋值多维数组:

$user->extra_attributes->set('school.class', 1001);
$user->extra_attributes->get('school.class');
$user->extra_attributes->get('school.foobar', 'default');
$user->save();

file

这应该比操作多维数组要更加方便。

搜索

扩展包包还帮助我们除了了 extra_attributes 字段的搜索

User::withExtraAttributes('position', 'php')->get();
User::withExtraAttributes('position', 'php')->toSql();
User::withExtraAttributes('school->class', '1001')->get();
User::withExtraAttributes('school->class', '1001')->toSql();

可以使用 toSql 查看一下最后查询的 sql 语句。

file

扩展包增加的这个 withExtraAttributes 可以方便的用于 Json 数据查询。

代码版本控制

$ git add -A
$ git commit -m 'spatie/laravel-schemaless-attributes'

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~