PHP 7 和 Laravel 8 使用私有变量序列化模型
PHP 7 and Laravel 8 serialize model with private variables
我正在将一个项目从 PHP 5.4,Laravel 4.2 升级到 PHP 7.4,Laravel 8。
使用 PHP 5.4 和 Laravel 4.2,我会 serialize()
具有关系和私有变量的模型
存储在redis中。当用户完成更改后,我们将其存储到数据库并从 Redis 中删除。
使用 PHP 5.4 和 Laravel 4.2,使用 serialize()
效果很好。
使用 PHP 7.4 和 Laravel 8,使用 serialize()
不包括我的模型中的私有变量
序列化时。我需要将我的模型与所有加载的关系和私有变量一起存储在 redis 中
当用户与模型交互时。
如何让 PHP 7.4 和 Laravel 8 序列化我的模型,包括私有变量?
class MyParent extends Model
{
private $privatevalueone = 1;
private $privatevaluetwo = 2;
public function childeh()
{ return $this->hasOne('ChildEh'); }
public function childbee()
{ return $this->hasMany('ChildBee'); }
public function childsea()
{ return $this->hasMany('ChildSea'); }
// there are a total of 11 relations
public function calc()
{
// - does calculations that can change model properties in relations
// and properties in the parent model.
// - stores values needed while the model is cached using private variables,
// the private variables are only needed while cached and not needed when
// written to DB
}
}
/**
* With PHP 5.4, Laravel 4.2, using serialize preserved
* the entire model, including private variables in the model
*
* With PHP 7.4, Laravel 8, using serialize does not
* include the private variables in the model,
*/
public function cacheSet($key, $model)
{
Redis::set($key, serialize($model));
}
public function cacheGet($key)
{
return unserialize(Redis::get($key));
}
感谢@nice_dev 的回复。
我的解决方案是将以下特征添加到我的模型中,它会执行您所引用的操作:
\Illuminate\Queue\SerializesModels
我正在将一个项目从 PHP 5.4,Laravel 4.2 升级到 PHP 7.4,Laravel 8。
使用 PHP 5.4 和 Laravel 4.2,我会 serialize()
具有关系和私有变量的模型
存储在redis中。当用户完成更改后,我们将其存储到数据库并从 Redis 中删除。
使用 PHP 5.4 和 Laravel 4.2,使用 serialize()
效果很好。
使用 PHP 7.4 和 Laravel 8,使用 serialize()
不包括我的模型中的私有变量
序列化时。我需要将我的模型与所有加载的关系和私有变量一起存储在 redis 中
当用户与模型交互时。
如何让 PHP 7.4 和 Laravel 8 序列化我的模型,包括私有变量?
class MyParent extends Model
{
private $privatevalueone = 1;
private $privatevaluetwo = 2;
public function childeh()
{ return $this->hasOne('ChildEh'); }
public function childbee()
{ return $this->hasMany('ChildBee'); }
public function childsea()
{ return $this->hasMany('ChildSea'); }
// there are a total of 11 relations
public function calc()
{
// - does calculations that can change model properties in relations
// and properties in the parent model.
// - stores values needed while the model is cached using private variables,
// the private variables are only needed while cached and not needed when
// written to DB
}
}
/**
* With PHP 5.4, Laravel 4.2, using serialize preserved
* the entire model, including private variables in the model
*
* With PHP 7.4, Laravel 8, using serialize does not
* include the private variables in the model,
*/
public function cacheSet($key, $model)
{
Redis::set($key, serialize($model));
}
public function cacheGet($key)
{
return unserialize(Redis::get($key));
}
感谢@nice_dev 的回复。 我的解决方案是将以下特征添加到我的模型中,它会执行您所引用的操作:
\Illuminate\Queue\SerializesModels