假设我有两种型号的“汽车”和“国产”,它们使用的是同一张桌子,名为“汽车”。例如:
cars
id | brand | type
0 | bmw | foreign
1 | audi | domestic
2 | ford | domestic“汽车”模型使用的是整个“汽车”表。但是,当我调用‘have’模型时,只有将'type‘列设置为’have‘的行才会被使用和影响。所以当我这么做的时候
$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'自定义模型的表名。有办法约束自定义表吗?
发布于 2016-09-22 14:42:37
我不相信你能抑制你喜欢它的雄辩的模型,但作为一个解决办法,你可以尝试这个方法覆盖:
在Domestic.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']);然后删除您创建的国内模型,它不再需要:-)
发布于 2016-09-22 14:26:52
希望这能帮到你..。
$cars = Car::all(); // returns all cars
$domestics = Domestic::where('type', 'domestic')->get(); // returns domestic carshttps://stackoverflow.com/questions/39641507
复制相似问题