I have 4 models:
- Stream
- Field
- Document
- Result
I then have below relationships defined:
Stream.php
:
public function fields()
{
return $this->hasMany(Field::class);
}
public function documents()
{
return $this->hasMany(Document::class);
}
Field.php
:
public function stream()
{
return $this->belongsTo(Stream::class);
}
public function result()
{
return $this->hasOne(Result::class);
}
Document.php
:
public function stream()
{
return $this->belongsTo(Stream::class);
}
Result.php
:
public function field()
{
return $this->hasOne(Field::class);
}
Now, my users can upload documents to a stream, and my users can create many fields on a stream.
When a document is uploaded to a stream,for each field defined, the document content will be parsed according to some logic I have created.
The end result of this parsing, should be saved to the database (results
).
I can do this now, by:
$document = Document::find(1);
foreach($stream->fields as $field)
{
$content = myParseFunction($document->content);
$field->save(['content' => $content]);
}
This will create a result for each field on the stream. Like, if my Stream had 2 fields:
results
table:
id | field_id | content
1 | 1 | Lorem ipsum
2 | 2 | Another ipsum
Whenever I upload a new document however, the result will be overwritten.
As each uploaded documents content is unique, how can I save the result for the field and specific document.
Like, if my Stream still have 2 fields, but I upload 2 documents:
results
table:
id | field_id | document_id | content
1 | 1 | 1 | Lorem ipsum
2 | 2 | 1 | Another ipsum
3 | 1 | 2 | Another unique content
4 | 2 | 2 | Yet another unique content