简体   繁体   English

在Laravel 4中通过迁移脚本创建MySQL视图

[英]Create MySQL view by migration script in Laravel 4

I'm trying to create view in MySQL in Laravel by migration script. 我正在尝试通过迁移脚本在Laravel中创建MySQL视图。 How can we create MySQL view by migration script in Laravel 4? 我们如何通过Laravel 4中的迁移脚本创建MySQL视图?

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, eg 然后,从应用程序中的其他位置访问视图,您可以像查询任何其他模型一样查询它,例如

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-paginate http://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. 真的,我想你必须小心这样的东西才能进行任何迁移,所以也许这不是什么大问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM