【问题标题】:create collections for each collection exist in relations attribute of laravel collections为每个集合创建集合存在于 laravel 集合的关系属性中
【发布时间】:2019-12-15 06:10:25
【问题描述】:

我有两个模型 Product 和 Price。这两个模型具有 一对多关系(one(Product) many(Price))并且这种关系有效正确。

我想从产品集合中提取价格属性,并为该产品集合中存在的每个价格创建产品集合数组,并且每个产品集合只有一个价格属性。

当我想制作新的产品集合时,每个产品的最新价格都存在于价格集合数组中

    $products = Product::find("bf88c08cc82b1afc801db2c184266c7b");
    $products->load("price");

    $newPrices=collect();
    $newProducts = collect();

    $products->price->map(function($price) use ($newPrices) {

            $newPrices->push($price); // extract prices from product collection
        });
        foreach ($newPrices as $newprice) { //for each price create new  product collection
              $hlp=$products;
             $hlp->unsetRelation("price");
             $hlp->setRelation("price",$newprice);
             $newProducts->push($hlp);
        }

但所有 $newProducts 的最后一个价格项目都存在于价格数组中

【问题讨论】:

  • 克隆解决了我的问题。 $hlp=clone($products);

标签: php laravel laravel-collection


【解决方案1】:

正如提问者在 cmets 中所说,以下代码解决了它:

$hlp = clone($products);

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2018-09-22
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多