Laravel Eloquent ORM - 如何在单个函数中保存多个实例


Laravel Eloquent ORM - how to save multiple instances in a single function

我有一个简单的私人消息程序,可以将消息发送给其他用户。他们可以将消息发送给多个人,就像普通电子邮件一样。但是,当我循环访问收件人以将消息添加到每个收件人的数据库中时,它只保存其中一个。

我是否需要为每个循环创建一个消息模型的新实例?

消息控制器:

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;
}

您的Message@sendMessage方法是递归更新相同的确切模型,而不是创建新模型。

正如Ali Gajani所说,这最好在控制器中完成。您没有在控制器中提供执行此操作的尝试,但那里可能也发生了同样的问题。

以下是您的MessagesController@store方法的外观(未经测试):

public function store() {
    $input = Input:all();
    // Validate the message data
    if( ! $this->isValid($input, $this->message))
        return Redirect::back()->withInput()->withErrors($this->message->inputErrors);
    $string = App::make('StringClass');
    for($i = 0; $i < count($input['recipients']); $i++) {
        // save new message to DB
        $message = $this->message->create(array(
            'sender'    => intval(Auth::id()),
            'recipient' => intval($input['recipients'][$i]),
            'subject'   => $string->nullifyAndStripTags($input['subject']),
            'body'      => $string->nullifyAndStripTags($input['body'], '<b><p><br><a><h1><h2><h3><h4><h5><h6><i><blockquote><u><ul><ol><li>')
        ));
        // You can now access the newly created message in this iteration
        // via $message.
        // If it wasn't created, $message->exists will be false. 
    }
    Session::put('adminSuccessAlert', 'Message sent.');
    return Redirect::to('admin/messages');
}

现在,我们使用Message@create递归创建,而不仅仅是更新同一模型的属性。

我没有合并会返回Failed to add message to DB.的错误检查,因为无论如何Message@sendMessage总是返回 true,但您可以相当轻松地合并事务以确保所有消息发送或不发送消息。