要做到這一點有一個很好的文章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