2016-11-23 2 views
0

Laravel에서 모든 모델은 기본 모델을 확장합니다.Laravel의 기본 모델 확장

laravel eloquent 모델에는 $ dates라는 보호 된 배열 속성이 있습니다. 이 배열에 추가되는 모든 날짜는 자동으로 Carbon 인스턴스로 변환됩니다.

비슷한 기능을 가진 기본 모델을 확장하고 싶습니다. 예를 들어 보호 된 $ times 속성이있는 경우. 모든 시간 속성은 Carbon 인스턴스로 변환됩니다.

어떻게 하시겠습니까?

미리 감사드립니다.

답변

0

원하는 것은 무엇이든지 쉽습니다. 기본적인 PHP 지식. 당신이 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의 모델을 확장 추가하려면

, 단순히 $dates 배열

에 추가

그러면 모든 모델이 \Illuminate\Database\Eloquent\Model

대신 \App\MyModel 클래스를 확장하면됩니다.
관련 문제