1

I have an application witch has two tables 'album' and 'photo', Where photo has a foreign_key to album.id. I use a transaction for storing the data in the database.

The problem occurs when I save the photo. It fails on:

$photo->albumId = Album::model()->findByAttributes('albumOtherId')->id; 

because there is no record of the album in the database and the findByAttributes returns NULL.

Is there any way to do this inside the transaction?

1
  • Can you provide the transaction and all other code as well? It's hard to tell what may be happening from that one line. Thank you! Commented Oct 14, 2011 at 12:48

2 Answers 2

1

I know this is an old question but I found myself looking for an answer for this same problem today. I could not believe that the only way to solve this was creating the "foreing key" first without using transaction. I don't know if the OP had the same situation but for my transaction, I needed only the ability to do a rollback, since I was deleting and updating other tables, but I didn´t need the foreign key checks (only for this transaction). So, before the first query I added the following (MySQL):

$transaction = $connection->beginTransaction(); $sqlForeingKeyDisable = 'SET foreign_key_checks = 0;'; $command = $connection->createCommand($sqlForeingKeyDisable); $command->execute(); 

This allowed me to use the rollback() and commit() with no problems. Hope I could help.

Sign up to request clarification or add additional context in comments.

Comments

0

so what I would do, is check if Album::model()->findByAttributes('albumOtherId')->id === NULL

then if it is, create a new album or ask the user to create the album. You have to create the album because of the relation, if you don't, it will never save as it depends on their being an album.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.