php - How to use a customized/restrained table for a model in laravel? -


let's have 2 models 'car' , 'domestic' use same table named 'cars'. example:

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

the 'car' model uses whole 'cars' table is. when call 'domestic' model rows have 'type' column set 'domestic' used , affected. when do:

$cars = car::all(); // returns cars  $domestics = domestic::all(); // returns domestic cars  domestic::create(['brand'=>'fiat']); // creates car domestic type 

we can customize table name model protected $table = 'cars'. there way restrain custom table?

i dont believe can restrain eloquent model how it, workaround can try method overrides:

in domestic.php add methods:

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

but kind of dirty solution , dont it. in case make scope domestic cars in cars model:

public function scopedomestic($query){      return $query->where('type', '=', 'domestic');  } 

then query domestic cars this:

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

as storing new domestic cars entries, add following static class in car model:

public static function createdomestic($attributes){      return cars::create(['type' => 'domestic'] + $attributes);  }     

and store new domestic cars this:

cars::createdomestic(['brand'=>'fiat']); 

then delete domestic model created, no longer needed :-)


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -