Reputation: 1114
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';
}
Upvotes: 2
Views: 3358
Reputation: 87719
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() );
Upvotes: 12
Reputation: 8019
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.
Upvotes: 2