Merge pull request #3027 from CihanSenturk/add-import-has-row-data-check

Add import has row data check
This commit is contained in:
Cüneyt Şentürk 2023-08-17 13:05:24 +03:00 committed by GitHub
commit 25fabbfe90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 63 additions and 1 deletions

View File

@ -29,8 +29,16 @@ abstract class Import implements HasLocalePreference, ShouldQueue, SkipsEmptyRow
public $user;
public $model;
public $request_class = null;
public $with_trashed = false;
public $columns = [];
public $has_row = [];
public function __construct()
{
$this->user = user();
@ -209,4 +217,41 @@ abstract class Import implements HasLocalePreference, ShouldQueue, SkipsEmptyRow
return str_replace($dependent_rules, $batch_rules, $rules);
}
//This function is used in import classes. If the data in the row exists in the database, it is returned.
public function hasRow($row)
{
// must be models and columns
if (empty($this->model) || empty($this->columns)) {
return false;
}
/* This function is called for each row.
This check is done in order not to query again for each row.
When the model to which the query is thrown changes, the new query should be discarded.
*/
if (! $this->has_row || ! $this->has_row instanceof $this->model) {
$this->has_row = $this->model::withoutEvents(function () {
if ($this->with_trashed) {
// This query should be used if there is no deleted_at field in the table or if the deleted data is to be retrieved.
return $this->model::withTrashed()->get($this->columns)->each(function ($data) {
$data->setAppends([]);
});
} else {
return $this->model::get($this->columns)->each(function ($data) {
$data->setAppends([]);
});
}
});
}
$search_value = [];
//In the model, the fields to be searched for the row are determined.
foreach ($this->columns as $key) {
$search_value[$key] = isset($row[$key]) ? $row[$key] : null;
}
return in_array($search_value, $this->has_row->toArray());
}
}

View File

@ -11,10 +11,20 @@ class Transactions extends Import
{
use TraitsTransactions;
public $model = Model::class;
public $request_class = Request::class;
public $columns = [
'number',
];
public function model(array $row)
{
if (self::hasRow($row)) {
return;
}
return new Model($row);
}
@ -29,8 +39,15 @@ class Transactions extends Import
$row['category_id'] = $this->getCategoryId($row, $real_type);
$row['contact_id'] = $this->getContactId($row, $real_type);
$row['document_id'] = $this->getDocumentId($row);
$row['parent_id'] = $this->getParentId($row);
$row['parent_id'] = $this->getParentId($row) ?? 0;
return $row;
}
public function prepareRules($rules): array
{
$rules['number'] = 'required|string';
return $rules;
}
}