如何在laravel中使用自定义/约束表


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

假设我有两个模型'Car'和'Domestic',它们使用同一个名为'cars'的表。为例:

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

'Car'模型使用整个'cars'表。但是当我调用"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'为模型定制表名。有没有办法约束自定义表?

我不相信你可以约束雄辩的模型,但作为一种变通方法,你可以尝试这个方法覆盖:

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

至于存储新的国内汽车条目,我将在您的Car模型中添加以下静态类:

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