【问题标题】:Laravel Push Item into hasManyRelation BuilderLaravel 将项目推送到 hasManyRelation Builder
【发布时间】:2020-06-14 12:42:50
【问题描述】:

在 laravel 模型中我有一个关系

public function photos()
{
   return $this->hasMany(Photo::class, 'item_id');
}

它返回与项目相关联的图像。现在我想在特定类别和品牌的所有产品中添加一个附加图像。所以从逻辑上讲,我得到了项目,如果它属于必需的部分,我想推送一张图片。我将代码修改为如下所示。

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany|Builder
     */
    public function photos()
    {
        if($this->category_id = 10 && $this->brand_id ==1){
            /**
             * Add an additional image in specific type of products, here apple phones
             */
            $photos = Photo::where('item_id', $this->id)->get();
            $additionalPhoto = new Photo();
            $additionalPhoto->item_id = $this->id;
            $additionalPhoto->image_name = 'https://si.wsj.net/public/resources/images/RV-AK835_INNOVA_P_20130614181900.jpg';
            $additionalPhoto->image_resized = false;
            $photos->push($additionalPhoto);
           return $photos;
        }else{
            return $this->hasMany(Photo::class, 'item_id');
        }
    }

当我在推送照片后执行dd($photos) 时,它会给出预期的结果。但唯一的事情是它适用于收集而不是关系。此关系已在多个地方使用,因此我不想将其更改为返回集合。

这样的推送数据是可能的

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    我认为不应该用这种逻辑来改变关系方法,因为它会以某种方式破坏关系。

    要使用现有关系进行推送,您可以在控制器中使用类似的内容:

    //Retrieve products
    Product::where('category_id', 10)
        ->whereHas('brand', function ($q) {
            $q->where('id', 1);
        })
        //Your relationship. item_id is not needed, since the relationship is defined with it
        ->photos()->create([
            'image_name' => 'https://si.wsj.net/public/resources/images/RV-AK835_INNOVA_P_20130614181900.jpg',
            'image_resized' => false
        ]);
    

    我没有对此进行测试,但是以类似的方式使用它,您可以保持关系并使用它直接添加数据。

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 1970-01-01
      • 2019-10-01
      • 2015-11-25
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多