Laravel Eloquent 支持 MariaDb 动态列

2022-01-07 00:00:00 sql mysql laravel yii2

对于 Maria-DB 和 MySQL 中支持的 动态 列,我们有 JSON 列类型.对于我们的一个项目,我们应该为 Maria-DB(而不是 Mysql)实现一个数据库.

For Dynamic column supported in Maria-DB and in MySQL we have JSON column type. For one of our projects, we should be implementing a database for Maria-DB (not Mysql).

使用yii2支持动态列-dynamic-ar 包.

The Dynamic Column is supported using yii2-dynamic-ar package.

如何覆盖Laravel 中的Eloquent orm 来添加dynamic-columns.在 Yii 包中,将这个特性添加到 ActiveRecord 这个类可以覆盖 ActiveRecord

how can can override Eloquent orm in Laravel to add dynamic-columns. in the Yii package which added this feature to ActiveRecord this classes can override ActiveRecord class

Yii 框架中的实现类以支持 ActiveRecord ORM:

implementations classes in Yii framework to support in ActiveRecord ORM:

  1. DynamicActiveRecord.php
  2. DynamicActiveQuery.php

推荐答案

我刚刚创建了使用 eloquent 和查询生成器处理 MariaDB 动态列的包.

I just created package for handling MariaDB dynamic Column using eloquent and query builder.

要安装软件包,请运行以下命令:

To install package run this command:

composer require halalsoft/laravel-dynamic-column

您可以通过添加 HasDynamicColumn trait 并使用 Dynamic 作为转换到模型的属性来开始使用该包.

You can start using the package by adding the HasDynamicColumn trait and use Dynamic as attribute cast to your models.

示例:

use IlluminateDatabaseEloquentModel;
use HalalsoftLaravelDynamicColumnDynamic;
use HalalsoftLaravelDynamicColumnHasDynamicColumn;

class MyModel extends Model
{
    use HasDynamicColumn;
    protected $casts
        = [
            'the_column' => Dynamic::class,
        ];
}

现在您可以使用 eloquent 或查询构建器使用动态列,如 json 列:

Now You can use dynamic column like json column using eloquent or query builder:

$modelData = MyModel::find(1);

$columnData = $modelData->the_column;

$columnData['data1'] = 'value';
$columnData['data2'] = 'value2';


$modelData->the_column = $columnData;

$modelData->save();

您也可以将数据字段创建为数组

You can also create data field as array

$newData = MyModel::create([
    'other_column' => 'this just another column data',
    'the_column' => ['data1'=>'value1','data2'=>'value2']
]);

要更新您使用的 json 字段/键,您可以在调用更新方法时使用 -> 运算符:

to update a json field/key you use, you may use the -> operator when calling the update method:

$page->update(['content->data1' => 'value1new']);

或者您仍然可以使用普通数组更新整列:

or you can still update whole column using normal array:

$page->update(['content' => ['data1'=>'value1new','data2'=>'value2new']]);

您可以使用updateOrCreate()firstOrCreate()等其他方法设置为数组

You can set as array using other method like updateOrCreate(), firstOrCreate(), etc.

这个包还支持查询生成器使用:

This package also support query builder using:

Model::query()->where('the_column->data1', 'value1')->first();

这个包仍然是新的,如果有任何问题或请求,请转到github issue

This package is still new, if any issue or request just go to github issue

相关文章