Search code examples
phplaravellaravel-9laravel-relations

How to use the relationship with BelongsToMany in Eloquent


I'm having trouble how to use the belongsToMany method of Laravel to create a relationship. I don't fully understand the description of the parameters. I have the following situation:

Fields of table products:

  • id
  • ...
  • product_unique_identifier

Fields of table product_images:

  • id
  • app_image_id
  • product_unique_identifier

Fields of table app_images:

  • id
  • ...

Now as you can imagine, I want to use in my Product model as well as in my AppImage model a relationship to the other table using the product_images table. The thing is, that the column product_unique_identifier is not the identity field in the products table, but a field of type string.

One product can have multiple images - one image is always related to one product.

I already tried this in my AppImage model:

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

This is not working as expected. I already had a look into the Laravel framework code (https://github.com/laravel/framework/blob/9.x/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php), but the explanations of the parameters is still not clear to me (which are pivot and related fields as described in the comments of the properties).


Solution

  • Try this

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