在 Laravel 4 中通过迁移脚本创建 MySQL 视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24546950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create MySQL view by migration script in Laravel 4
提问by Harry Shah
I'm trying to create view in MySQL in Laravel by migration script. How can we create MySQL view by migration script in Laravel 4?
我正在尝试通过迁移脚本在 Laravel 中的 MySQL 中创建视图。我们如何在 Laravel 4 中通过迁移脚本创建 MySQL 视图?
回答by morphatic
How about this? Haven't tested it, but I think it should work.
这个怎么样?还没有测试过,但我认为它应该可以工作。
class CreateMyView extends Migration {
public function up()
{
DB::statement( 'CREATE VIEW myview AS SELECT [your select statement here]' );
}
public function down()
{
DB::statement( 'DROP VIEW myview' );
}
}
And then you can create a model to access it:
然后你可以创建一个模型来访问它:
class MyView extends Eloquent {
protected $table = 'myview';
}
And then to access the view from elsewhere in your app you can query it like you would any other model, e.g.
然后要从应用程序的其他地方访问视图,您可以像查询任何其他模型一样查询它,例如
MyView::all(); // returns all rows from your view
MyView::where( 'price', '>', '100.00' )->get(); // gets rows from your view matching criteria
Props go to the following which provided info on how to do this:
道具转到以下内容,其中提供了有关如何执行此操作的信息:
http://laravel.io/forum/05-29-2014-model-with-calculated-sql-field-doesnt-paginatehttp://forumsarchive.laravel.io/viewtopic.php?pid=51692#p51692
http://laravel.io/forum/05-29-2014-model-with-calculated-sql-field-doesnt-paginate http://forumsarchive.laravel.io/viewtopic.php?pid=51692#p51692
CAVEAT
警告
Be careful if later migrations modify the tables underlying your view. The reason is that per the documentation:
如果以后的迁移修改了视图下的表,请小心。原因是根据文档:
The view definition is “frozen” at creation time, so changes to the underlying tables afterward do not affect the view definition. For example, if a view is defined as SELECT * on a table, new columns added to the table later do not become part of the view.
视图定义在创建时“冻结”,因此之后对基础表的更改不会影响视图定义。例如,如果视图在表上定义为 SELECT *,则稍后添加到表中的新列不会成为视图的一部分。
Really, I guess you'd have to be careful of stuff like that for any migration, so maybe this is not such a big deal.
真的,我想您必须在进行任何迁移时小心此类事情,所以也许这没什么大不了的。