如何使用与《雄辩》中属于许多人的关系



我在如何使用Laravel的belongsToMany方法来建立关系时遇到了麻烦。我不完全理解参数的描述。我有以下情况:

products的字段:

  • id
  • product_unique_identifier

product_images的字段:

  • id
  • app_image_id
  • product_unique_identifier

app_images的字段:

  • id

现在,您可以想象,我想在我的Product模型中以及在我的AppImage模型中使用product_images表与另一个表的关系。问题是,列product_unique_identifier不是products表中的标识字段,而是string类型的字段。

一个产品可以有多个图像 - 一个图像始终与一个产品相关。

我已经在我的AppImage模型中尝试过这个:

public function product() {
return $this->belongsToMany(AppModelsProductProduct::class, 'product_images','app_image_id','product_unique_key','id','product_unique_key');
}

这未按预期工作。我已经查看了 Laravel 框架代码 (https://github.com/laravel/framework/blob/9.x/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php),但我仍然不清楚参数的解释(它们是属性注释中所述的透视和相关字段)。

在您的情况下,您可以使用 belongsToMany 方法定义关系,如下所示:

在产品型号中:

public function images()
{
return $this->belongsToMany(AppImage::class, 'product_images', 'product_unique_identifier', 'app_image_id');
}

在应用映像模型中:

public function products()
{
return $this->belongsToMany(Product::class, 'product_images', 'app_image_id', 'product_unique_identifier');
}

试试这个

public function product() {
return $this->belongsToMany(AppModelsProductProduct::class, 'product_images','app_image_id','product_unique_identifier');
}

最新更新