Search code examples
phplaravelmany-to-manyrelationshiprelation

In laravel project with many to many relation, should I put the "value of attribute" in which table of database?


I have a laravel project with many to many relation and multi language. I used Laravel-Translatable package for multi language.
This program stores a large number of files with their attributes.
Each attribute is shared between several files. But each attribute has a different value in each file.
Table and their relationship is like this photo: tables diagram

should I put the attribute_value in which table?? thank you


Solution

  • Add attribute_value to the attrib_file table. Because for each connection with a file attribute_value should be different. On the other hand, each file stores number of attribute values. That's why attrib_file pivot table fits best. How to retrieve information from pivot table is given in the documentation:

    $attr = App\Attribute::find(1);
    foreach($attr->files as $file) {
      echo $file->pivot->attribute_value;
    }
    

    Make sure to add ->withPivot('attribute_value') end of return $this->belongsToMany('App\Models\File') in your relation method. It should be something like this within the Attribute model:

    ..
    public function files() {
        return $this->belongsToMany('App\Models\File')->withPivot('attribute_value');
    }