Php Laravel将项目推送到HasmanyRelationBuilder中
在拉威尔模型中,我有一个关系Php Laravel将项目推送到HasmanyRelationBuilder中,php,laravel,eloquent,Php,Laravel,Eloquent,在拉威尔模型中,我有一个关系 public function photos() { return $this->hasMany(Photo::class, 'item_id'); } 它返回与项目关联的图像。现在我想在所有特定类别和品牌的产品中添加一个附加图像。所以从逻辑上讲,我得到的是一个项目,如果它属于必需的部分,我想推送一个图像。我修改了代码,使其看起来像这样 /** * @return \Illuminate\Database\Eloquent\Relat
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)操作时,它会给出预期的结果。但唯一的问题是,它将与集合而不是关系一起工作。此关系已在多个位置使用,因此我不想将其更改为返回集合
可以通过关系来推送这样的数据我认为不应该用这种逻辑改变关系方法,因为它会以某种方式破坏关系 要使用现有关系推送,您可以在控制器中使用类似以下内容:
//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
]);
我没有测试过这个,但是以类似的方式使用它,您可以保持您的关系并直接使用它添加数据