2017-05-06 1 views
7

나는 초심자 인 laravel에 대한 나의 질문은 누군가에게 이상 할 수 있습니다. 글쎄, 내 질문에 어떻게 Laravel Model 클래스를 내 마이 그 레이션 후 데이터베이스의 모든 필드를 만들지 않습니다 엔티티 쓸 수 있습니다. 예를Laravel Model에서 NotMapped 엔티티를 작성하는 방법은 무엇입니까?

class JobseekerModel extends Model 
{ 
    use SoftDeletes; 
    protected $table='dbl_jobseekers'; 
    protected $primaryKey='id'; 
    protected $fillable=[ 
     'FirstName', 
     'MiddleName', 
     'LastName', 
     'Dob', 
     'Education', 
     'DesireField', 
     'Skill', 
     'SpecialSkill', 
     'Experience', 
     'Location', 
     'HomeAddress', 
     'Salary', 
     'Comenteries', 
     'Resume' 
    ]; 
    protected $dates = ['deleted_at']; 
} 

를 들어이 지금은 그러나 나는 데이터베이스 열로 만들 싫어, 내 모델에서 'PagedListSize'라는 이름의 또 다른 속성을 추가하려면, 내 모델입니다. 그러면 어떻게해야합니까?

예를 들어 나는이 작업을 수행하기 위해 내가 할 수 어떻게

그래서
[NotMapped] 
public int PagedListSize {set; get;} 

처럼 기록 된, .Net FrameworkNotMapped 속성을 사용하는 것이 익숙해입니다. laravel에서 이것을 할 방법이 있습니까? 내가 일하고있다 Laravel 5.4

+1

좀 더 자세히 설명해 주실 수 있습니까? 계산해야하는 fieald가 필요합니까? 아니면 수업의 단순한 속성이 필요합니까? – huuuk

+0

글쎄, 데이터베이스의 열을 만들지 않는 클래스의 간단한 속성이 필요합니다. 그러나 나는'Controller'에서'view'와'view'에서'Controller'로 데이터를 전달할 수 있습니다.내 계산 목적에 따라이 속성을 사용합니다. 아무것도. – gdmanandamohon

+0

@lazycoder 질문에, 당신은 어디에 직렬화 할 속성이 필요하다고하셨습니까? 받아 들여진 대답이 나의 것과 유일한 차이점이 있기 때문에 클래스를 json 데이터로 변환 할 때 속성을 직렬화 할 수있는 방법이 설명되어 있습니다. –

답변

0

에서이 작업을 수행하는 가장 좋은 방법 : 여기

$tag->full_name = "Christos Lytras"; 
echo $tag->first_name; // prints "Christos" 
echo $tag->last_name; // prints "Lytras" 

는 어설프게 스크린 샷입니다 실제로 Laravel은 custom Mutators입니다. 또한 모델의 json 또는 어레이 출력 덤프에 표시되도록 변경자를 구성 할 수 있습니다. 예 : PagedListSize을 위해 우리가 할 수 :

public functionGetPagedListSizeAttribute() 
{ 
    return #some evaluation; 
} 

protected $appends = array('pagedListSize'); 

이 방법 pagedListSize는 모델이 JSON 또는 배열 등의 serialized 때마다 사용할 수 있습니다 또한 필드로 직접 사용할 수 있지만하지 않습니다.

+0

그것이 내가 기대하고 있었던 것이다! !!!!!! – gdmanandamohon

2

보호 속성을 Laravel Model에 추가 할 수 있습니다. 필드 이름과 충돌하지 않는 한 괜찮습니다. 게다가, Laravel을 사용하면 마이그레이션이 모델이 아닌 DB 구조를 결정하므로 필드를 자동으로 생성하는 위험을 감수하지 않아도됩니다. 실제로 기본 모델은 기본적으로 속성없이 작동합니다.

편집 : 기본 패키지의 예는 User.php

<?php 

namespace App; 

use Illuminate\Notifications\Notifiable; 
use Illuminate\Foundation\Auth\User as Authenticatable; 

class User extends Authenticatable 
{ 
    use Notifiable; 

    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'name', 'email', 'password', 
    ]; 

    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 

    /** 
    * You can add some properties here 
    * will require getter and/or setters 
    * does not need to be fillable 
    */ 
    protected $someLogicalProperty; 

} 

실제 DB 구조는 마이그레이션 (2014_10_12_000000_create_users_table.php)에 정의되어

Schema::create('users', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->string('name'); 
    $table->string('email')->unique(); 
    $table->string('password'); 
    $table->rememberToken(); 
    $table->timestamps(); 
}); 

당신이 볼 수 있듯이, 타임 스탬프 및 토큰은 사용자 모델에도 나열되지 않습니다. 모든 fillable이 정의되면 사용자 객체에 public 속성으로 설정할 수 있지만 ($user->name = 'Bob';), create()/save() 상속 된 메소드에 인수로 전달할 수도 있습니다. 엔티티는 Laravel에서 직접 액세스 할 수 없지만 여기에 있으며 필요하면 더 구체적으로 지정할 수 있습니다.

+0

이 솔루션과 관련된 코드를 제안 해 주시겠습니까? – gdmanandamohon

4

사용자 지정 Mutators을 만들어 Laravel의 데이터베이스 필드에 매핑하지 않고 이러한 종류의 사용자 지정 속성을 가질 수 있습니다.

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

    public function setFullNameAttribute($value) 
    { 
     list($this->first_name, $this->last_name) = explode(' ', $value); 
    } 
} 

하고 모델 초기화 한 후 다음과 같이 사용할 수 있습니다 :

Artisan Tinker Example