如何使用 Laravel 模型访问数据库视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26593270/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:20:23  来源:igfitidea点击:

How to access db views using Laravel models?

phppostgresqllaravel

提问by RSAdmin

I am porting a Postgres-backed web app to Laravel 4.2, and I can't see a way to utilize the existing eight or so summation views which are built in the psql db. These views preform various aggregation and averaging functions, and as such are properly part of the schema as they illustrate the relationships between the table entities.

我正在将 Postgres 支持的 Web 应用程序移植到 Laravel 4.2,但我看不到一种方法可以利用 psql 数据库中内置的现有八个左右的求和视图。这些视图执行各种聚合和平均功能,因此它们是模式的适当组成部分,因为它们说明了表实体之间的关系。

Surely someone has had to use db views with the active record style interface of Laravel? How do you go about it?

肯定有人不得不在 Laravel 的活动记录样式界面中使用 db 视图吗?你是怎么做的?

回答by The Alpha

Your question is about database views and if I'm not wrong then you are talking about the dynamic table that gets created on the fly, for example, in MySql, it's possible to create a Viewusing something like this:

您的问题是关于数据库视图,如果我没有错,那么您正在谈论动态创建的动态表,例如,在 中MySql,可以View使用以下内容创建一个:

CREATE VIEW students AS SELECT * FROM profiles where type='student' ORDER BY id;

So, it'll allow to query the dynamic table which is the studentsview here, for example:

因此,它将允许查询动态表,即students此处的视图,例如:

select * from students;

This will return the filtered data from studentsview. So, if I'm right about your question then I think you are able to use Eloquentjust like you use for real tables, for example, to create an Eloquentmodel for students viewyou can simply create it using something like this:

这将从students视图中返回过滤后的数据。因此,如果我对您的问题是正确的,那么我认为您可以Eloquent像使用真实表格一样使用,例如,Eloquent为学生创建模型,view您可以简单地使用以下内容创建它:

class ViewStudent extends Eloquent {

    protected $table = 'students';
}

So, now you can use this model as usully you may use for other tables, for example;

所以,现在你可以像往常一样使用这个模型,你可能会使用其他表,例如;

$students = ViewStudent::all();

It's just the same way. Since you asked for psqlso I'm not sure about the syntax of that or how it works in that system but I believe it's possible same way.

这只是同样的方式。既然你psql这么要求,我不确定它的语法或它在该系统中的工作方式,但我相信它可能以同样的方式运行。