programing

로드 시 Larabel/Allustive 모델에 사용자 지정 속성을 추가하시겠습니까?

yoursource 2022. 11. 1. 22:18
반응형

로드 시 Larabel/Allustive 모델에 사용자 지정 속성을 추가하시겠습니까?

Laravel/Eloquent 모델이 로드될 때 RedBean의 모델과 마찬가지로 커스텀 속성/속성을 추가할 수 있으면 좋겠습니다. $model->open()★★★★★★ 。

예를 들어, 현재 컨트롤러에는 다음과 같은 기능이 있습니다.

public function index()
{
    $sessions = EventSession::all();
    foreach ($sessions as $i => $session) {
        $sessions[$i]->available = $session->getAvailability();
    }
    return $sessions;
}

루프를 생략하고 "available" Atribute를 이미 설정해 둘 수 있으면 좋겠습니다.

설명서에 설명된 일부 모델 이벤트를 사용하여 개체가 로드될 때 이 속성을 첨부하려고 시도했지만 지금까지 성공하지 못했습니다.

주의:

  • 'available'은 기본 테이블의 필드가 아닙니다.
  • $sessions되고 있기 에 API의 JSON 하고 있습니다.라음$session->available().

는 " " " "가 입니다.Model의 »toArray()method는 기본 테이블의 컬럼과 직접 관련되지 않은 모든 접근자를 무시합니다.

Taylor Otwell이 여기서 언급했듯이, "이는 의도적이고 성과적인 이유 때문입니다."단, 이를 실현하기 위한 간단한 방법이 있습니다.

class EventSession extends Eloquent {

    protected $table = 'sessions';
    protected $appends = array('availability');

    public function getAvailabilityAttribute()
    {
        return $this->calculateAvailability();  
    }
}

$appends 속성에 나열된 속성은 적절한 접근자를 추가한 경우 모델의 어레이 또는 JSON 형식에 자동으로 포함됩니다.

오래된 답변(Larabel 버전 4.08 미만):

가장 좋은 은 가가 the the the the the the the the the the the the the the the the the the the the the the the the 를 덮어쓰는 것이다.toArray() 및 중 합니다.

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        $array['upper'] = $this->upper;
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

또는 커스텀액세스가 많은 경우는, 그것들을 모두 루프 해 적용합니다.

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        foreach ($this->getMutatedAttributes() as $key)
        {
            if ( ! array_key_exists($key, $array)) {
                $array[$key] = $this->{$key};   
            }
        }
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

Laravel Archent 문서 페이지의 마지막 내용은 다음과 같습니다.

protected $appends = array('is_admin');

하면 새로운 할 수 방법은, 「」와 같이 방법을 하지 않아도 .예를 들어 다음과 같은 추가 작업이 필요 없습니다.::toArray()

작성만 하면 됩니다.getFooBarAttribute(...)및를 추가합니다.foo_bar로로 합니다.$appends

「」의을 ,getAvailability() to 는 methodgetAvailableAttribute()당신의 메서드가 접근자가 되어 당신은 그것을 읽을 수 있게 될 것입니다.->available을 사용법

문서: https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

편집: 속성은 "가상"이므로 기본적으로는 개체의 JSON 표현에 포함되지 않습니다.

하지만 이걸 발견했어->toJson()이 호출했을 때 커스텀 모델액세스가 처리되지 않았습니까?

어레이 내에서 Atribute를 강제로 반환하려면 Atribute 배열에 Atribute를 키로 추가합니다.

class User extends Eloquent {
    protected $attributes = array(
        'ZipCode' => '',
    );

    public function getZipCodeAttribute()
    {
        return ....
    }
}

테스트하지 않았습니다만, 현재의 설정으로 테스트하는 것은 매우 간단할 것입니다.

뭔가 비슷한 게 있었어내 모델에 속성 사진이 있습니다. 여기에는 저장소 폴더에 있는 파일의 위치가 포함됩니다.이미지는 base64 인코딩된 상태로 반환되어야 합니다.

//Add extra attribute
protected $attributes = ['picture_data'];

//Make it available in the json response
protected $appends = ['picture_data'];

//implement the attribute
public function getPictureDataAttribute()
{
    $file = Storage::get($this->picture);
    $type = Storage::mimeType($this->picture);
    return "data:" . $type . ";base64," . base64_encode($file);
}

스텝 1: Atribute 정의$appends
스텝 2: 그 Atribute의 Accessor를 정의합니다.
예:

<?php
...

class Movie extends Model{

    protected $appends = ['cover'];

    //define accessor
    public function getCoverAttribute()
    {
        return json_decode($this->InJson)->cover;
    }

사용할 수 있습니다.setAttribute사용자 지정 속성을 추가하는 모형 함수

사용자 테이블에 first_name과 last_name이라는 이름의 열이 2개 있고 전체 이름을 가져오고 싶다고 가정합니다.다음 코드를 사용하여 달성할 수 있습니다.

class User extends Eloquent {


    public function getFullNameAttribute()
    {
        return $this->first_name.' '.$this->last_name;
    }
}

이제 다음과 같은 풀네임을 얻을 수 있습니다.

$user = User::find(1);
$user->full_name;

내 구독 모델에서 구독이 일시 중지되었는지 확인해야 합니다.내가 한 방법은 이렇다

public function getIsPausedAttribute() {
    $isPaused = false;
    if (!$this->is_active) {
        $isPaused = true;
    }
}

뷰 템플릿에서는$subscription->is_paused결과를 얻기 위해.

getIsPausedAttribute커스텀 어트리뷰트를 설정하는 형식입니다.

및 용도is_paused뷰에서 속성을 가져오거나 사용할 수 있습니다.

제 경우 빈 컬럼을 만들고 접근자를 설정하면 정상적으로 동작합니다.접근자는 dob 컬럼부터 Array()까지 사용자의 연령을 채웁니다.

public function getAgeAttribute()
{
  return Carbon::createFromFormat('Y-m-d', $this->attributes['dateofbirth'])->age;
}

언급URL : https://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load

반응형