Answer the question
In order to leave comments, you need to log in
How to search by name to get id?
Hello. I have 2 tables. Authors and Books (each with its own fields). The books table has an author id field that was displayed. I made it through the view so that instead of the author's id in this table, the author's name from the table with the authors would be displayed. Made an export of the Books table. As expected, he exported, along with other fields, the author's name from the other table, and not the id.
Now I'm doing a table import.
And I need to search the database by name and find the author's id by substituting it.
Or I quote the words of my teacher
You don't have to create a new author. it is necessary to search in the database by its name and get its id, so that later it can be substituted into the created model of the book
no. nothing needs to be cleaned up. You are loading data from a file. instead of the author's id, you have his name. you take this name, make a query to the database (search by the name of the author), get data on this author and take his id from them
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost ) {
$model->fName = UploadedFile::getInstance($model, 'fName');
if ($fName =$model->upload()) {
//путь к файлу
if (($handle = fopen($fName, 'r')) !== false) {
while (($row = fgetcsv($handle, 1000, ',')) !== false) {
if ($row[0]=='ID' and $row[0]=='#'){
continue;}
$model = new Kniga1();
$model->name = $row [2];
$model-> id_avtor1 = $row [4];
$model->creation_date = $row [5];
if ($model->validate()) {
$model->save();
} else {
$model->save();
print_r($model->errors);
}
}
fclose($handle);
};
//... код после импорта
}
}
return $this->render('upload', ['model' => $model]);
}
Answer the question
In order to leave comments, you need to log in
Good morning.
This is not true.
if ($model->validate()) {
$model->save();
} else {
$model->save();
print_r($model->errors);
}
public static function getIdAuthor($name){
return Author::find()->select('id')->where('name=:name',[':name' => $name])->column();
}
$model-> id_avtor1 = Author::idAuthor($row[4]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question