Yii 事务与关系
我有一个应用程序,有两个表“相册”和“照片”,其中照片有一个 album.id 的外键。我使用事务将数据存储在数据库中。
当我保存照片时出现问题。失败:
$photo->albumId = Album::model()->findByAttributes('albumOtherId')->id;
因为数据库中没有该专辑的记录,并且 findByAttributes 返回 NULL。
有什么办法可以在交易中做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这是一个老问题,但今天我发现自己正在寻找同一问题的答案。我不敢相信解决这个问题的唯一方法是首先创建“外键”而不使用事务。我不知道OP是否有相同的情况,但对于我的事务,我只需要执行回滚的能力,因为我正在删除和更新其他表,但我不需要外键检查(仅用于此)交易)。因此,在第一个查询之前,我添加了以下内容(MySQL):
这使我可以毫无问题地使用 rollback() 和 commit() 。希望我能帮忙。
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):
This allowed me to use the rollback() and commit() with no problems. Hope I could help.
所以我要做的是检查Album::model()->findByAttributes('albumOtherId')->id === NULL,
如果是,则创建一个新相册或要求用户创建相册。由于关系,您必须创建相册,如果不这样做,它将永远不会保存,因为这取决于它们是否是相册。
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.