2014-07-03 34 views

回答

24

這個怎麼樣?沒有測試過,但我認爲它應該可以工作。

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'); 
    } 

} 

然後你就可以創建一個模型來訪問它:

class MyView extends Eloquent { 

    protected $table = 'myview'; 

} 

然後從你的應用程序的其他地方訪問視圖可以查詢它像使用任何其他的模式,例如

MyView::all(); // returns all rows from your view 
MyView::where('price', '>', '100.00')->get(); // gets rows from your view matching criteria 

道具去哪個就如何做到這一點提供的信息如下:

http://laravel.io/forum/05-29-2014-model-with-calculated-sql-field-doesnt-paginate http://forumsarchive.laravel.io/viewtopic.php?pid=51692#p51692

CAVEAT

要小心,如果以後遷移修改表的基本視圖。原因是,per the documentation

視圖定義在創建時是「凍結的」,因此後來對基礎表的更改不會影響視圖定義。例如,如果視圖在表上定義爲SELECT *,則稍後添加到表中的新列不會成爲視圖的一部分。

真的,我想你必須小心這樣的東西,因爲任何遷移,所以也許這不是什麼大不了的。