Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I do a safe test and set using Doctrine and Symfony transaction?
    primarykey
    data
    text
    <p>I'd like to understand how to do a safe "test and set" operation with Doctrine and Symfony.</p> <p>I'm building a meeting scheduling system. I have an entities called </p> <p>MeetingTime, Teacher and Student</p> <p>MeetingTime has, among other things, a nullable many to one relationship with Student and a many to one with Teacher.</p> <p>I want to enforce that the student property of meetingTime can only be saved if the properly is currently null. i.e., one student shouldn't be able to overwrite another. The first student to book the time wins. It seems like a transaction will do this.</p> <p>I'm doing this:</p> <pre><code> $saved = true; try { $em-&gt;transactional(function($em) use($mtId, $student) { $mt = $em-&gt;getRepository('MyBundle:MeetingTime')-&gt;find($mtId); if (is_null($mt-&gt;getStudent())) { $mt-&gt;setStudent($student); $em-&gt;persist($mt); } else { throw new Exception(); } }); } catch(Exception $e) { $saved = false; } if (!$saved) { // flash "Sorry,, somebody else just grabbed that time". } </code></pre> <p>My UI will cope with most of this by not showing a "Book this time" button on the page if that time is taken but of course the database has the final say if two people do it at the same time.</p> <p>That seems to work but is this the right way to do it? Is it transactionally safe?</p> <p>I implemented it first with an additional "Booking" entity with a one to one to MeetingTime and a many to one with Student and a unique constraint on MeetingTime. That works okay but having Student as a property of MeetingTime is better because I also want MeetingTime to have a unique constraint on Student and Teacher combined because a student can only book one meeting with a teacher.</p> <p>I know I should probably create my own Exception class so that I know the type of exception. I should also allow it to be happy if the correct student is already set.</p> <p>In case it matters, the database is PostgreSQL. I'm sure this could be done very efficiently with a trigger but ... that's a whole world I haven't been into and it would be nice to keep this db agnostic.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload