I am writing a parser that saves data from a third-party site. At the entered page address, I receive an array of the following type:

array(1) { ['category']=>"lorem ipsum" ['description']=>'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.' ['page']=>'За словесными горами '; ['desc_page']=>'Далеко-далеко за словесными горами в стране гласных и согласных живут рыбные тексты. Вдали от всех живут они в буквенных домах на берегу Семантика большого языкового океана.' }; 

Well, since categories can be repeated for different pages, the question is:

How can I properly save to the database if there is no category in the database with the name "lorem ipsum" ?

  • what is right? if you don’t write an explicit verification request, it means writing a trigger that will add the missing category and substitute it with id - splash58

1 answer 1

Like that:

  $categoryId = Category::find() ->select('id') ->where(['title'=>"lorem ipsum"]) ->scalar(); if (!$categoryId ){ $newCategory = new Category(); $newCategory->setAttributes( ['title'=>"lorem ipsum"] ); if($newCategory->save()){ $categoryId = $newCategory->id; } }