2016-08-04 71 views
1

對某人來說這可能很簡單。但對我而言,我完全迷失了。誰能給我擡起頭使用MySQL視圖中Laravel 5.我一直在尋找相關的職位一段時間,但沒有線索不同的是:Mysql查看Laravel 5.2

DB::statement("Create View") 

DB::statement("Drop View") 

但這並不按門鈴。任何幫助,任何線索,任何指導表示讚賞。 預先感謝

我的情況

我有一個員工表與其他表保存僱員的各種屬性分別如Appointmentpostinghealthfamily等等等等大多數這些表格有一個屬性Is_current來表示員工的當前記錄。因此,無論何時我想用最新的記錄顯示員工檔案或從這些表格中檢索最新的記錄,我都不想從每個表格中逐一檢索。我只想編譯view中的最新記錄,並隨時從中檢索。

我希望你明白我的要求,對不起我的英文不好

+0

你想達到什麼確切的畫面? – jaysingkar

+0

然後我會用那個信息更新我的問題 – jonju

回答

1

要做到這一點有一個很好的文章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.上面的代碼從給定的文章中複製並根據您的需要進行更改。

-1
'options' => [ 
      \PDO::ATTR_EMULATE_PREPARES => true 
] 

enter image description here 添加代碼爲 「配置/ database.php中」 見下文 Show Example