Laravel Eloquent支持MariaDb动态列 [英] Laravel Eloquent supporting MariaDb dynamic column
问题描述
对于 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
.在将此功能添加到 ActiveRecord
的 Yii
包中,此类可以覆盖 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
实现类,以在 ActiveRecord
ORM中支持:
implementations classes in Yii
framework to support in ActiveRecord
ORM:
推荐答案
我刚刚使用雄辩的查询构建器创建了用于处理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
特征并开始使用 Dynamic
作为模型的属性来开始使用该程序包.
You can start using the package by adding the HasDynamicColumn
trait and use Dynamic
as attribute cast to your models.
一个例子:
use Illuminate\Database\Eloquent\Model;
use Halalsoft\LaravelDynamicColumn\Dynamic;
use Halalsoft\LaravelDynamicColumn\HasDynamicColumn;
class MyModel extends Model
{
use HasDynamicColumn;
protected $casts
= [
'the_column' => Dynamic::class,
];
}
现在,您可以使用雄辩的或查询的生成器来使用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字段/密钥,可以在调用update方法时使用->
运算符:
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问题
This package is still new, if any issue or request just go to github issue
这篇关于Laravel Eloquent支持MariaDb动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!