2016-09-22 14:14
浏览 47


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

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:


    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:


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

    解决 无用
    打赏 举报

相关推荐 更多相似问题