我在如何使用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');
}