I'm building a messaging system using ReadBean 3.5.1 (with MySQL). Each user can have multiple messages, so this is a simple one-to-many relationship for RedBean, like so:
$sender = R::load('user', 1);
$message = R::dispense('message');
$message->stuff = "Hello world";
$sender->ownMessage[] = $message;
What I want to do now is associate the recipient user with the message using a RedBean abstraction. I can get the ID of the recipient and store it in a column in the messages
table manually, but is there a way I can do this with RedBean instead?
The solution to this is actually a bit backwards to what was posted. You need to create a message and assign two user models to it instead of the other way round. Here's an example:
// Make some models
list($sender, $recipient) = R::dispense('user', 2);
$message = R::dispense('message');
// Set some data
$sender->name = 'Sender';
$recipient->name = 'Recipient';
$message->title = "Hello world";
// Associate users and message
$message->sender = $sender;
$message->recipient = $recipient;
// Store everything
R::store($message);
Really easy. RedBean takes care of storing the updated user info when R::store($message)
is called. The messages table then looks like this:
+----+-------------+-----------+--------------+
| id | title | sender_id | recipient_id |
+----+-------------+-----------+--------------+
| 6 | Hello world | 3 | 4 |
+----+-------------+-----------+--------------+