如何在laravel中为模型使用定制/限制桌子?
问题描述:
比方说,我有两个模型'汽车'和'国内',使用同一个表'汽车'。例如:如何在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'
。有没有办法限制自定义表格?
答
我不相信你能克制雄辩的模型,你是怎么想的,但作为一种解决方法,你可以试试这个方法覆盖:
在你的家庭。 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']);
然后删除您创建的国内模型,它不再需要:-)
答
希望这有助于你..
$cars = Car::all(); // returns all cars
$domestics = Domestic::where('type', 'domestic')->get(); // returns domestic cars
您不需要两个模型进行该操作。你可以用Cars模型和附加的where子句来定义国内汽车。 – 2016-09-22 15:25:12