I have 4 models:
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
I think the result is also determined by the document, as you are parsing a document for a for a field. I would also link the documents to theuse the Result table ans store the results there. One result would be determinded by the document id and the field id.
Result
public function fields()
{
return $this->hasMany(Field::class);
}
public function documents()
{
return $this->hasMany(Document::class);
}
Document
public function results()
{
return $this->hasMany(Result::class);
}
Field
public function stream()
{
return $this->belongsTo(Stream::class);
}
public function result()
{
return $this->hasOne(Result::class);
}
And then:
$document = Document::find(1);
$result = new Result();
foreach($stream->fields as $field)
{
$content = myParseFunction($document->content);
$result->save(['field_id' => $field->id, 'document_id'=>$document->id, 'content' => $content]);
}