要做到这一点有一个很好的文章here
我将展示从文章中的一些代码。
改变基类像以下:
public function save(array $options = [])
{
$this->toWriteMode();
try {
$saved = parent::save($options);
} catch (\Exception $e) {
$this->toReadMode();
throw $e;
}
$this->toReadMode();
return $saved;
}
protected $readOnly = [];
protected $readOnlyCache = [];
public function save(array $options = [])
{
$this->toWriteMode();
$this->cacheReadOnly();
try {
$saved = parent::save($options);
} catch (\Exception $e) {
$this->toReadMode();
throw $e;
}
$this->toReadMode();
$this->restoreReadOnly();
return $saved;
}
protected function cacheReadOnly()
{
$this->readOnlyCache = [];
foreach ($this->readOnly as $key) {
$value = $this->getAttributeValue($key);
$this->readOnlyCache[$key] = $value;
$this->__unset($key);
}
}
protected function restoreReadOnly()
{
foreach ($this->readOnlyCache as $key => $value) {
$this->setAttribute($key, $value);
}
}
创建雇员模型如下:
class Employee extends BaseModel
{
protected $table = 'employees';
protected $fillable = ['name'];
protected $guarded = ['id'];
public function people()
{
return $this->hasMany('Person');
}
}
创建EagerEmployee类,如下所示:
class EagerEmployee extends Employee
{
protected $readFrom = 'employeeView'; //Use your view name
protected $readOnly = ['person_ids'];
public function getPersonIdsAttribute($ids)
{
return $this->intArrayAttribute($ids);
}
}
这个类将从视图中读取数据,我们可以保存并重新使用平时如此。它将读取只读属性,并在保存时对其进行适当处理。
新的intArrayAttribute()
方法只是将从视图返回的逗号分隔的id字符串转换为整数数组。
我们可以在内部使用Employee,但如果我们需要这些额外的只读属性,比如在api响应中,我们可以使用EagerEmployee类。 P.S.上面的代码从给定的文章中复制并根据您的需要进行更改。
你想达到什么确切的画面? – jaysingkar
然后我会用那个信息更新我的问题 – jonju