douyanyan1123 2016-09-22 14:14
浏览 47
已采纳

如何在laravel中为模型使用定制/限制表?

Let's say I have two models 'Car' and 'Domestic' that use the same table named 'cars'. As example:

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

The 'Car' model uses the whole 'cars' table as it is. But when I call the 'Domestic' model then only the rows that have the 'type' column set to 'domestic' will be used and affected. So that when I do:

$cars = Car::all(); // returns all cars

$domestics = Domestic::all(); // returns domestic cars

Domestic::create(['brand'=>'fiat']); // creates a car with domestic type

We can customize the table name for the model with protected $table = 'cars'. Is there a way to restrain the custom table?

  • 写回答

2条回答 默认 最新

  • douweng7308 2016-09-22 14:42
    关注

    I dont believe you can restrain eloquent model how you would like it, but as a workaround you can try this method overrides:

    In your Domestic.php add this 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 it is kind of dirty solution and i dont really like it. In your case i would make scope for domestic cars in your Cars model:

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

    then i would query all domestic cars like this:

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

    as for storing new domestic cars entries, i would add following static class in your Car model:

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

    And i would store new domestic cars like this:

    Cars::createDomestic(['brand'=>'fiat']);
    

    Then delete Domestic model you created, its no longer needed :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求直线方程 使平面上n个点在直线同侧并且距离总和最小
  • ¥50 java算法,给定试题的难度数量(简单,普通,困难),和试题类型数量(单选,多选,判断),以及题库中各种类型的题有多少道,求能否随机抽题。
  • ¥50 rk3588板端推理
  • ¥250 opencv怎么去掉 数字0中间的斜杠。
  • ¥15 这种情况的伯德图和奈奎斯特曲线怎么分析?
  • ¥250 paddleocr带斜线的0很容易识别成9
  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题