制作Laravel模型使用复杂查询作为表

时间:2016-03-16 07:13:29

标签: sql laravel orm eloquent erp

我正在开发一个与ERP生产数据库连接的Web应用程序,并且在传递给我的控制器和以不同方式修改它们的视图之前,通过具有许多连接和别名的复杂SQL查询来检索数据。

结果可能是,例如,包含每次购买的所有相关信息的产品数组,例如型号,序列号,客户等,并且在较小规模的应用程序中,这些肯定都会存储在同一个应用程序中。表

然而,因为我从一个非常复杂的ERP解决方案中抽出来,这些细节来自许多不同的表格,但我希望将其视为我模型中的单个表格。

有没有办法实现这一点,以便我像往常一样使用Eloquent?像Product::all()这样的东西不起作用,虽然我可以调用Product::getWhere($serial)这样的自定义方法,但我更倾向于以雄辩的方式执行此操作,因为它更容易使分页更好用。

以下是我的查询的概念:

SELECT
[PSerials].[ElementID] AS [ProductElementID],
[PSerials].[SerialNumber] AS [SerialNumber],
[PSerials].[SNStatus] as [ProductStatus],
[PSerials].[JobID] AS [JobID],
[Element].[Desc] AS [Description],
[PSerials_UD].[Prog] AS [ProgramNum],
[PSerials_UD].[Elec] AS [ElecPrint],
[PSerials_UD].[SinglePHVolt_c] AS [SinglePHVolt],
[PSerials_UD].[SinglePHAmp_c] AS [SinglePHAmp],
[PSerials_UD].[ThreePHVolt_c] AS [ThreePHVolt],
[PSerials_UD].[ThreePHAmp_c] AS [ThreePHAmp],
[PSerials_UD].[Notes_c] AS [Notes],
[PSerials_UD].[WarrantyExpDate_c] AS [WarrantyExpDate],
[QuoteDtl].[QuoteNum] AS [QuoteNum],
[QuoteDtl].[QuoteComment] AS [QuoteComment],
[OrderDtl].[RequestDate] AS [ShipDate],
[Customer].[CustID] AS [CustomerID],
[Customer].[Name] AS [CustomerName],
[Customer1].[CustID] AS [ShipToCustomerID],
[Customer1].[Name] AS [ShipToCustomerName]
FROM Erp.PSerials AS PSerials
INNER JOIN Erp.Element AS Element ON
PSerials.Company = Element.Company AND PSerials.ElementID = Element.ElementID
AND (Element.ProdCode = 'MACH' AND Element.ClassID = 'MAC')
INNER JOIN Erp.PSerials_UD AS PSerials_UD ON
PSerials_UD.ForeignSysRowID = PSerials.SysRowID
LEFT OUTER JOIN Erp.PProd AS PProd ON PProd.JobID = PSerials.JobID
LEFT OUTER JOIN Erp.OrderDtl AS OrderDtl ON PProd.Company = OrderDtl.Company
AND PProd.OrderNum = OrderDtl.OrderNum AND PProd.OrderLine = OrderDtl.OrderLine
LEFT OUTER JOIN Erp.QuoteDtl AS QuoteDtl ON OrderDtl.QuoteNum = QuoteDtl.QuoteNum
AND OrderDtl.QuoteLine = QuoteDtl.QuoteLine
LEFT OUTER JOIN Erp.Customer AS Customer ON  OrderDtl.Company = Customer.Company
AND OrderDtl.CustNum = Customer.CustNum
LEFT OUTER JOIN Erp.Customer AS Customer1 ON PSerials.Company = Customer1.Company
AND PSerials.ShipToCustNum = Customer1.CustNum

我将它放在我的Product模型上的静态变量中,然后根据需要使用自定义函数简化SQL查询,但这并不优雅,并且它不是使用起来很有趣,以下是我如何使用这些查询的示例:

public static function getWhere($serial)
{
    $query = DB::select(DB::raw(Self::$baseQuery));
    $collection = new \Illuminate\Support\Collection($query);

    $product = $collection->where("SerialNumber", $serial)->first();

    return $product;
}

我是否可以让我的模型简单地将这样的查询看作是一个简单的表格,或者是否有其他方法可以实现这一目标?

更新

感谢Zamrony P. Juhara在下面的建议,我能够成功创建一个SQL视图并告诉我的Products模型引用就像一个表:

class Product extends Model
{
    protected $table = 'dbo.ProductInfo';
}

现在Product::all()按预期工作。

关于Peh指出的限制,这个应用程序纯粹是为了查看ERP软件中存在的数据,并且不需要更新或删除任何记录,因此在这种情况下,SQL视图绝对是完美的。 / p>

1 个答案:

答案 0 :(得分:3)

您可以将SQL命令转换为VIEW(CREATE VIEW),然后像模型中的普通表一样使用它。