2016-11-23 7 views
0

Laravelでは、すべてのモデルがベースモデルを拡張します。Laravelのベースモデルを拡張する

laravel雄弁モデルには、$ datesという保護された配列属性があります。この配列に追加される各日付は、自動的にCarbonインスタンスに変換されます。

同様の機能を持つ基本モデルを拡張したいと思います。たとえば、保護された$ times属性を使用します。すべての時間属性はCarbonインスタンスに変換されます

どうすればよいですか?

ありがとうございます。

答えて

0

あなたがしたいことは何でも簡単です。基本的なPHPの知識。

あなたは、いくつかの新しいパラメータを追加したい場合は、単に$dates配列

に追加し、Carbonインスタンスに変換するためのいくつかの他のフィールドを追加したい場合は

<?php 
namespace App; 

class MyModel extends \Illuminate\Database\Eloquent\Model 
{ 

    protected $awesomness = []; 

    /** 
    * override method 
    * 
    */ 
    public function getAttributeValue($key) 
    { 
     $value = $this->getAttributeFromArray($key); 

     // If the attribute has a get mutator, we will call that then return what 
     // it returns as the value, which is useful for transforming values on 
     // retrieval from the model to a form that is more useful for usage. 
     if ($this->hasGetMutator($key)) 
     { 
      return $this->mutateAttribute($key, $value); 
     } 

     // If the attribute exists within the cast array, we will convert it to 
     // an appropriate native PHP type dependant upon the associated value 
     // given with the key in the pair. Dayle made this comment line up. 
     if ($this->hasCast($key)) 
     { 
      return $this->castAttribute($key, $value); 
     } 

     // If the attribute is listed as a date, we will convert it to a DateTime 
     // instance on retrieval, which makes it quite convenient to work with 
     // date fields without having to create a mutator for each property. 
     if (in_array($key, $this->getDates()) && !is_null($value)) 
     { 
      return $this->asDateTime($value); 
     } 

     // 
     // 
     // that's the important part of our modification 
     // 
     // 
     if (in_array($key, $this->awesomness) && !is_null($value)) 
     { 
      return $this->doAwesomness($value); 
     } 

     return $value; 
    } 

    public function doAwesomness($value) 
    { 
     //do whatever you want here 
     return $value; 
    } 

} 
以下のようにちょうどlaravelのモデルを拡張するには

あなたのすべてのモデルは\Illuminate\Database\Eloquent\Modelの代わりに\App\MyModelのクラスを拡張する必要があります。

関連する問題