У меня есть простая программа личных сообщений, которая отправляет сообщения другим пользователям. Они могут отправлять сообщение не более чем одному человеку, как в случае обычной электронной почты. Тем не менее, когда я перебираю получателей, чтобы добавить сообщение в базу данных для каждого из них, его сохранение только одного из них.Laravel Eloquent ORM - как сохранить несколько экземпляров в одной функции
Нужно ли создавать новый экземпляр модели сообщений для каждого цикла?
MessagesController:
public function store() {
// Validate the message data
if(! $this->isValid(Input::all(), $this->message))
return Redirect::back()->withInput()->withErrors($this->message->inputErrors);
if(! $this->message->sendMessage(Input::all())) {
//log error to logger
$errorNum = $this->logger->createLog('MessagesController', 'store', 'Failed to add message to DB.', Request::url(), Request::path(), 8);
Session::put('adminDangerAlert', 'Error #'. $errorNum . ' - Something went wrong attempting to save the message to the database. Contact an administrator if this continues.');
return Redirect::back()->withInput();
}
Session::put('adminSuccessAlert', 'Message sent.');
return Redirect::to('admin/messages');
}
Сообщение Модель:
public function sendMessage($input) {
$string = App::make('StringClass');
for($i = 0; $i < count($input['recipients']); $i++) {
//save new message to DB
$this->sender = intval(Auth::id());
$this->recipient = intval($input['recipients'][$i]);
$this->subject = $string->nullifyAndStripTags($input['subject']);
$this->body = $string->nullifyAndStripTags($input['body'], '<b><p><br><a><h1><h2><h3><h4><h5><h6><i><blockquote><u><ul><ol><li>');
$this->save();
}
return true;
}
В идеале рекурсия должна выполняться в контроллере. –
@AliGajani Пробовал это тоже. Все еще добавлено только 1 сообщение в базу данных. –