Laravel 4:一个模型可以服务几个DB表吗? [英] Laravel 4: can one model serve several DB tables?
问题描述
$ data = DB :: select('select * from toronto where id =?',array($ id));
我想做的是开始使用口才。我是Laravel的新人,只是想知道是否有可能有一个模型工作与几个表,smth像:
class City扩展Eloquent {
protected $ table_a ='toronto';
protected $ table_b ='vancouver';
protected $ table_c ='montreal';
}
。有很多方法,这里有一个:
创建一个城市模型,在其构造函数中要求一个表名:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
public function __construct($ city,array $ attributes = :: __构造($属性);
$ this-> table = $ city;
}
}
要使用它,你会有使用表名实例化你的课程:
$ toronto = new City('toronto');
然后你可以做任何你想要的东西:
var_dump($ toronto-> where('id',701057) - > get());
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';
}
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() );
这篇关于Laravel 4:一个模型可以服务几个DB表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!