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

如何在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 :-)

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dscqrkvr9562034621 2016-09-22 14:26

    Hope this helps you..

    $cars = Car::all(); // returns all cars
    
    $domestics = Domestic::where('type', 'domestic')->get(); // returns domestic cars
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题