Fixed a bug where categories would be created even though they already existed.

This commit is contained in:
James Cole 2015-04-09 17:46:47 +02:00
parent 8f9b1b866b
commit 339c352505
2 changed files with 36 additions and 3 deletions

View File

@ -3,7 +3,7 @@
use Crypt;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App;
/**
* Class Category
*
@ -31,6 +31,39 @@ class Category extends Model
return $this->belongsToMany('FireflyIII\Models\TransactionJournal', 'category_transaction_journal', 'category_id');
}
/**
* @param array $fields
*
* @return Account|null
*/
public static function firstOrCreateEncrypted(array $fields)
{
// everything but the name:
$query = Category::orderBy('id');
foreach ($fields as $name => $value) {
if ($name != 'name') {
$query->where($name, $value);
}
}
$set = $query->get(['categories.*']);
/** @var Category $category */
foreach ($set as $category) {
if ($category->name == $fields['name']) {
return $category;
}
}
// create it!
$category = Category::create($fields);
if (is_null($category->id)) {
// could not create account:
App::abort(500, 'Could not create new category with data: ' . json_encode($fields));
}
return $category;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/

View File

@ -140,7 +140,7 @@ class JournalRepository implements JournalRepositoryInterface
// store or get category
if (strlen($data['category']) > 0) {
$category = Category::firstOrCreate(['name' => $data['category'], 'user_id' => $data['user']]);
$category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
$journal->categories()->save($category);
}
@ -193,7 +193,7 @@ class JournalRepository implements JournalRepositoryInterface
// unlink all categories, recreate them:
$journal->categories()->detach();
if (strlen($data['category']) > 0) {
$category = Category::firstOrCreate(['name' => $data['category'], 'user_id' => $data['user']]);
$category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
$journal->categories()->save($category);
}