Php 如何为laravel中的模型使用自定义/约束表?
假设我有两个型号“Car”和“national”,它们使用同一个名为“cars”的表。例如:Php 如何为laravel中的模型使用自定义/约束表?,php,laravel,Php,Laravel,假设我有两个型号“Car”和“national”,它们使用同一个名为“cars”的表。例如: cars id | brand | type 0 | bmw | foreign 1 | audi | domestic 2 | ford | domestic “Car”模型使用整个“cars”表。但是,当我调用“国产”模型时,只有将“type”列设置为“国产”的行才会被使用和影响。因此,当我这样做时: $cars = Car::all(); // returns all cars
cars
id | brand | type
0 | bmw | foreign
1 | audi | domestic
2 | ford | domestic
“Car”模型使用整个“cars”表。但是,当我调用“国产”模型时,只有将“type”列设置为“国产”的行才会被使用和影响。因此,当我这样做时:
$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'
自定义模型的表名。有没有办法限制自定义表?希望这对您有所帮助
$cars = Car::all(); // returns all cars
$domestics = Domestic::where('type', 'domestic')->get(); // returns domestic cars
我不相信你能抑制雄辩的模型,但作为一种解决方法,你可以尝试以下方法: 在您的homeline.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();
Cars::createDomestic(['brand'=>'fiat']);
至于存储新的国产车条目,我会在您的车型中添加以下静态类:
public static function createDomestic($attributes){
return Cars::create(['type' => 'domestic'] + $attributes);
}
我会像这样储存新的国产车:
Cars::domestic()->get();
Cars::createDomestic(['brand'=>'fiat']);
然后删除您创建的国内模型,不再需要:-)此操作不需要两个模型。您可以只使用汽车型号和定义国产汽车的附加where条款。