2013-06-03 10 views
16

방금 ​​새 웹 사이트를 시작했으며 Eloquent를 사용하려고했습니다. 데이터베이스를 파싱하는 과정에서, 설득력있는 확장 모델에 모든 종류의 생성자를 포함 시키면 빈 행이 추가된다는 사실을 알게되었습니다. 예를 들어,이 씨 뿌리는 실행 : 내 팀 클래스로이와Eloquent를 확장하는 클래스의 생성자

<?php 

class TeamTableSeeder extends Seeder { 

    public function run() 
    { 
     DB::table('tm_team')->delete(); 

     Team::create(array(
      'city' => 'Minneapolis', 
      'state' => 'MN', 
      'country' => 'USA', 
      'name' => 'Twins' 
      ) 
     ); 

     Team::create(array(
      'city' => 'Detroit', 
      'state' => 'MI', 
      'country' => 'USA', 
      'name' => 'Tigers' 
      ) 
     ); 
    } 

} 

을 : 간단하게 생성자를 제거

team_id | city | state | country | name | created_at   | updated_at   | deleted_at 
1  |  |  |   |  | 2013-06-02 00:29:31 | 2013-06-02 00:29:31 | NULL 
2  |  |  |   |  | 2013-06-02 00:29:31 | 2013-06-02 00:29:31 | NULL 

가 모두 함께 같이 일할 수있는 시더 수 있습니다 :

<?php 

class Team extends Eloquent { 

    protected $table = 'tm_team'; 
    protected $primaryKey = 'team_id'; 

    public function Team(){ 
     // null 
    } 
} 

하면이냅니다 예상했다. 정확히 내가 생성자에 대해 잘못된 것은 무엇입니까?

public function __construct(array $attributes = array()) 
{ 
    if (! isset(static::$booted[get_class($this)])) 
    { 
     static::boot(); 

     static::$booted[get_class($this)] = true; 
    } 

    $this->fill($attributes); 
} 

boot 메서드가 호출되고 booted 속성이 설정됩니다

+0

Eloquent는 자신 만의 생성자이기 때문에 일하는 것이 웅변적 인 모든 동작을 설정 해제했습니다. – crynobone

답변

25

당신은 당신이 Eloquent 클래스의 생성자를 보면 상황이 여기에 작동하도록 parent::__construct를 호출해야합니다. 이게 무슨 일을하는지 잘 모르지만 문제에 따라 관련이있는 것으로 보입니다 : attributes 배열을 얻기 위해 생성자를 리 팩터 화하여 상위 생성자에 넣으십시오.

class MyModel extends Eloquent { 
    public function __construct($attributes = array()) { 
     parent::__construct($attributes); // Eloquent 
     // Your construct code. 
    } 
} 
+0

+1 업데이트의 경우 첫 번째 코드는 -1입니다. 원인 : 재사용 가능성 ... 웅변적인'__construct()'가 변경되면 호환되지 않습니다 – Ifnot

+0

제대로 답변을 읽으면 데모 용 Eloquent 생성자가 복사되었습니다. –

+0

아, 네 말이 맞아. . 마지막 줄 설명과 업데이트에 대한 언급은 혼란 스러웠습니다. 응답의 첫 번째 코드는 일반적으로 빠른 복사/붙여 넣기 응답입니다. 어쩌면 내가 편집 한 것처럼 github 링크로 대체해야합니다. – Ifnot

1

laravel 3에서는 기본 값 "거짓"로 두 번째 매개 변수 '$ 존재'를 넣어해야합니다

업데이트 여기

는 필요한 코드입니다.

class Model extends Eloquent { 

    public function __construct($attr = array(), $exists = false) { 
     parent::__construct($attr, $exists); 
     //other sentences... 
    } 
} 
0

매개 변수를 전달할 수있는 일반적인 방법을 사용할 수 있습니다.

/** 
* Overload model constructor. 
* 
* $value sets a Team's value (Optional) 
*/ 
public function __construct($value = null, array $attributes = array()) 
{ 
    parent::__construct($attributes); 
    $this->value = $value; 
    // Do other staff...  
}