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条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况