2016-08-04 70 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