实际上,我已经使用以下步骤使用 PHP Artisan 为 Laravel 创建了一个 sql 视图。
步骤 1. 运行以下命令:
php artisan make:migration create_overall_report_views
第2步。
打开迁移文件并添加以下代码:
class CreateOverallReportView extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
DB::statement("
CREATE VIEW views_overall_report AS
(
SELECT er.user_id as user_id, e.id AS entities_id,
c.status_id AS status_id, s.name AS status_name
FROM `user_roles` er
LEFT JOIN elists e ON e.id=er.entities_id
LEFT JOIN `clists` c ON c.id=e.checklists_id
LEFT JOIN `status` s ON s.id = c.overall_status_id
WHERE s.slug = 'completed'
AND c.deleted_at IS NULL
)
");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement('DROP VIEW IF EXISTS views_overall_report');
}
}
第 3 步。通过 Laravel 查询调用和运行 SQL 视图
$items = $DB::table('views_overall_report')
->select('status_id', 'status_name',
$DB::raw('count(entities_id) as counts')
)
->groupBy('status_id')
->orderBy('counts' , 'desc')
->whereIn('user_id', Auth::user()->id())
->get();
print_r($items);
希望有所帮助。如果有人有更好的解决方案,请告诉我!!
原文由 rc.adhikari 发布,翻译遵循 CC BY-SA 4.0 许可协议
偶然发现了同样的问题并找到了解决方案@ http://programmingarehard.com/2013/11/10/eloquent_and_views.html/