2016-09-22 4 views
1

'cars'라는 테이블을 사용하는 'Car'와 'Domestic'의 두 모델이 있다고 가정 해 보겠습니다. 예 :laravel에서 모델에 대해 사용자 정의/제한 테이블을 사용하는 방법은 무엇입니까?

cars 
id | brand | type 
0 | bmw | foreign 
1 | audi | domestic 
2 | ford | domestic 

'자동차'모델은 전체 '자동차'테이블을 그대로 사용합니다. 그러나 'Domestic'모델을 호출하면 'type'열이 'domestic'으로 설정된 행만 사용되어 영향을받습니다. 그렇게 할 때 :

$cars = Car::all(); // returns all cars 

$domestics = Domestic::all(); // returns domestic cars 

Domestic::create(['brand'=>'fiat']); // creates a car with domestic type 

protected $table = 'cars'으로 모델의 테이블 이름을 사용자 정의 할 수 있습니다. 사용자 정의 테이블을 제지하는 방법이 있습니까?

+0

:-) 필요한 두 가지 모델을 삭제합니다. Cars 모델과 국내 자동차를 정의하는 추가 where 절만으로 할 수 있습니다. –

답변

1

나는 당신이 당신이 좋아하는 얼마나 설득력 모델을 억제 할 수 있다고 생각 해달라고 도움이되지만 해결 방법으로이 방법의 재정의를 시도 할 수 있습니다 :

당신의 가정에서. PHP는이 방법을 추가하십시오 :

public static function all() 
{ 
    $columns = is_array($columns) ? $columns : func_get_args(); 

    $instance = new static; 

    return $instance->newQuery()->where('type' => 'domestic')->get($columns); 
} 

public static function create(array $attributes = []) 
{ 
    $attributes = array('type' => 'domestic') + $attributes; 

    return parent::create($attributes); 
} 

그러나 그것은 더러운 솔루션의 일종이며 정말 그것을 좋아하지 않아. 귀하의 경우에는 내가 당신의 자동차 모델에서 국내 자동차에 대한 범위를 만들 것 :

public function scopeDomestic($query){ 

    return $query->where('type', '=', 'domestic'); 

} 

그럼 내가 이렇게 모든 국내 차량을 조회 할 것이다 : 새로운 국내 자동차 항목을 저장하는 등의

Cars::domestic()->get(); 

, 내가 추가 할 수 나는이 같은 새로운 국내 자동차를 저장하는 것

public static function createDomestic($attributes){ 

    return Cars::create(['type' => 'domestic'] + $attributes); 

}  

그리고 :

,369 당신의 자동차 모델에 정적 클래스를 다음
Cars::createDomestic(['brand'=>'fiat']); 

그리고 국내 사용자가 만든 모델, 해당 작업에 대한 당신은 필요 없어 더 이상

1

희망이 당신이 ..

$cars = Car::all(); // returns all cars 

$domestics = Domestic::where('type', 'domestic')->get(); // returns domestic cars