Laravel 4: can one model serve several DB tables?

2019-02-15 15:51发布

In my application I have several mysql tables: Toronto, Vancouver, Montreal, etc... and I am using the DB-class to work with them, eg.

$data = DB::select('select * from toronto where id = ?', array($id));

What I want to do is to start using Eloquent. I am new to Laravel and was just wondering if its possible to have one model work with several tables, smth like:

class City extends Eloquent {
      protected $table_a = 'toronto';
      protected $table_b = 'vancouver';
      protected $table_c = 'montreal';
}

2条回答
太酷不给撩
2楼-- · 2019-02-15 16:46

It cannot, but you can. There are many ways, here's one:

Create your a City model that asks for a table name in its constructor:

class City extends Eloquent {

    public function __construct($city, array $attributes = array())
    {
        parent::__construct($attributes);

        $this->table = $city;
    }

}

To use it you'll have to instantiate your class using the table name:

$toronto = new City('toronto');

Then you can do anything you want with it:

var_dump( $toronto->where('id',701057)->get() );
查看更多
beautiful°
3楼-- · 2019-02-15 16:47

You can do $model->setTable('mytable') once you have a model instanciated, but for multiple tables I would rather recommend you make one "base" model with all the functionality you need and then several other classes which extend this class but define their own table with protected $table = 'table'.

However, in your case it sounds like you shouldn't be keeping the data in separate database tables at all. If you can find a way to store the state as a column instead of in separate tables, that would be better.

查看更多
登录 后发表回答