All individual subscriptions are 50% off this week only!

4 months ago

Relationship belongsTo two columns

Posted 4 months ago by oliverbusk

I have three models:

  1. File
  2. Field
  3. Result

A file can have many fields, and a field can belong to many files. This gives me:


public function fields()
    return $this->hasMany(Field::class);


public function files()
    return $this->belongsToMany(Files::class);

Now, my users can upload files to my website and create fields. All files uploaded will "inherit" the fields.

A field could, for example, be called Invoice Number. My user can then add the invoice number from the uploaded file to the field.

However, as each uploaded file is unique, this means that the final field content will also be unique, thus requiring me to create a third model result.

I am not sure how to define this relationship because a result belongs to a field and a file.



id | name
1  | invoice1.pdf
2  | invoice2.pdf


id | name
1  | Invoice Number


id | file_id | field_id | content
1  | 1       | 1        | #1234
2  | 2       | 1        | #8888

I would then like to be able to get the result for the field, for a specific file, such as:

Filename = invoice1.pdf Fields = Invoice Number Results = #1234

Please sign in or create an account to participate in this conversation.