0

这是我添加了一个附加quantity列的 RecipeIngredientPivot 表模式。

-----------------------------------------------------
 id | ingredientID | recipeID | quantity
-----------------------------------------------------
| 1 | A001         | R001       | 100               |
| 2 | A002         | R001       | 50                |
| 3 | C004         | R001       | 23                |
| 4 | A001         | R002       | 75                |

通过仅使用 Pivot 而不是 ModifiablePivot,我能够为具有和作为兄弟quantity的 Pivot 表创建一个列。ingredient_idrecipe_id

extension RecipeIngredientPivot: Pivot {
    init(_ recipe: Recipe, _ ingredient: Ingredient, _ quantity: Double) throws {
        self.recipeID = try recipe.requireID()
        self.ingredientID = try ingredient.requireID()
        self.quantity = quantity
    }
}

但是,我不确定如何查询和获取食谱的数量。

extension Recipe {
    var ingredients: Siblings<Recipe, Ingredient, RecipeIngredientPivot> {
        return siblings()
    }

    var quantities: [Double] {
        // Not sure how to get this.
    }
}

任何帮助深表感谢。

4

1 回答 1

1

我想到了。在映射结果之前,我必须执行query(on.req)&并等待两者都成功完成。pivot(on: req)siblings()

let ingredientFuture = try recipe.ingredients.query(on: req).all()
let pivotFuture = try recipe.ingredients.pivots(on: req).all()

return ingredientFuture.and(pivotFuture).map { ingredients, pivots in
    for (ingredient,pivot) in zip(ingredients, pivots) {
        print("\(ingredient) - \(pivot.quantity)")
    }
}
于 2020-03-23T17:54:56.603 回答