簡體   English   中英

Propel 2:使用子查詢作為虛擬列的值

[英]Propel 2: Using a subquery as the value for a virtual column

我們有一個包含所有產品的表格和一個包含所有訂購商品的單獨表格。 訂購的商品基本上是訂購產品的副本,與其源產品(通過外鍵)有關,而附加數據僅與訂購商品相關,如訂購數量。

這樣我們就可以確保訂單數據的一致性,因為即使我們將來可能會刪除舊產品,舊訂單仍然會以訂單商品的形式包含所有訂購的產品。 訂單和訂單商品通過簡單的交叉引用表(如Propel文檔中的那個)連接,只有兩個字段order_id和item_id。

現在我必須實現一個計算尚未發貨的產品的訂購數量的功能,因此我們可以跟蹤我們仍有多少庫存可供銷售,以及實際已經銷售了多少,但不是尚未發貨。

為了實現這一點,我必須選擇與給定源產品相關的所有項目,這些項目僅屬於未發貨訂單,然后對這些項目的數量字段進行調整。 這看起來像Propel2中的以下內容:

$ordered_qty = ItemQuery::create()
    // Sum up the quantity of all ordered items and only select this one column
    ->withColumn('SUM(Item.Qty)', 'ordered_qty')
    ->select('ordered_qty')
    // join with the cross referencing table between orders and order items 
    // so we can join with the actual order data in the next step
    ->leftJoinOrderItemCrossRef()
    // join with the order data so that we can filter out 
    // already shipped (= archived) orders
    ->leftJoin('OrderItemCrossRef.Order')
    ->addJoinCondition('Order', 'Order.IsArchived != 1')
    // only find the items relating to the desired product
    ->where('Item.ProductId = ?', $product_id)
    ->groupByProductId()
    ->findOne(); 

此查詢的工作方式類似於魅力,findOne()返回尚未發貨的訂購數量。 但是單獨的查詢對我來說沒用,我需要將結果添加到產品模型中。

我想為ProductQuery添加一個自定義方法,它為每個產品添加了一個虛擬列'OrderedQty',所以我可以選擇所有這樣的產品:

$products = ProductQuery::create()
    ->withOrderedQty()
    ->find();

foreach($products as $product)
{
    echo 'Ordered Qty of ' . $product->getName() . ': ' . $product->getOrderedQty() . '\n';
}

但我不知道如何使用子查詢作為Propel中虛擬列的值。

如果我理解你的問題,你可以使用addSelectQuery方法達到預期的效果。 我沒有所需的表結構,所以我只是暗示它是如何工作的。

addSelectQueryfrom子句中將Criteria添加為subQuery。

// some query from item table
$itemQuery = \ItemQuery::create()->...;

$productQuery = \ProductQuery::create()
    ->addSelectQuery($itemQuery, 'item_query_result_alias', false);

在此之后你會得到一個像這樣的查詢carcase:

SELECT item.*
FROM item, (/* here will be the $itemQuery select */) AS item_query_result_alias

然后只需使用withColumn方法添加一個withColumn列:

$products = \ProductQuery::create()
    ->withColumn('item_query_result_alias.ordered_qty', 'ordered_qty')
    ->addSelectQuery($itemQuery, 'item_query_result_alias', false)
    ->find();

查詢將是:

SELECT item.*, item_query_result_alias.ordered_qty AS ordered_qty
FROM item, (/* here will be the $itemQuery select */) AS item_query_result_alias

得到結果:

var_dump($products->getFirst()->getVirtualColumn('ordered_qty'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM