Laravel 缓存数据,转为 JSON 存入,取出来后如何再赋值属性?以便与 save 等操作
引子
最近开发碰到个问题,在把数据写入缓存时候,我们得到的是stdclass,写入后只能 ToArray()
,转 json
存入。
那么当我们读取的时候呢?
你传给变量,但是!重要的来了,你这个变量之前是stdclass,是具有 laravel orm
的模型属性的!
那我们怎么办呢?
请看下文。
使用setRawAttributes 来追加属性
setRawAttributes 介绍
setRawAttributes 函数为新的数据库对象赋予属性值,并且进行 sync,标志着对象的原始状态:
public function setRawAttributes(array $attributes, $sync = false)
{
$this->attributes = $attributes;
if ($sync) {
$this->syncOriginal();
}
return $this;
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
这个原始状态的记录十分重要,原因是 save 函数就是利用原始值 original 与属性值 attributes 的差异来决定更新的字段。
下面贴我的代码片段
// 读取缓存
$cacheData = $redisWarp->readCache($cacheName,$redis);
if ( !empty($cacheData) )
{
$result = collect();
// 遍历填充model 属性
foreach($cacheData as $m)
{
$model = app(Article::class);
BaseCacheTrait::fillModel( $model, $m );
$result->push($model);
}
return $result;
}
是如何填充属性的?
下面我们进入 BaseCacheTrait::fillModel( $model, $m );
中来看这个 是如何填充属性的?
/**
* 初始化model,使其能正常使用save等操作
*
* @param Object $model
* @param array $attrs
* @return Object
*/
static public function fillModel($model, $attrs=[])
{
//这里必须使用内置函数赋值,否则外面使用save函数时,会将改动的都进行insert操作导致失败
//也可以使用 newFromBuilder 方法重新创建一个
if ( !empty($attrs) )
{
$model->setRawAttributes($attrs,true);
}
else
{
//如果没有传入 属性数组,外部需要保证自己有进行过数据初始化,
//这里只是对数据进行同步处理
$model->syncOriginal();
}
//$model->forceFill($cache_data);
//需要将此属性设置为true,便于外部使用时使用save 操作时能进行更新
$model->exists = true;
return $model;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接