2016-09-22 24 views
1

比方說,我有兩個模型'汽車'和'國內',使用同一個表'汽車'。例如:如何在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子句來定義國內汽車。 – 2016-09-22 15:25:12

回答

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); 

}  

,我會存儲新的國產車是這樣的:

Cars::createDomestic(['brand'=>'fiat']); 

然後刪除您創建的國內模型,它不再需要:-)

1

希望這有助於你..

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

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