繁体   English   中英

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

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

我有一个简单的私人消息程序,可以将消息发送给其他用户。 与普通电子邮件一样,他们可以将消息发送给多个人。 但是,当我遍历收件人以向每个收件人添加一条消息到数据库时,它仅保存其中一个。

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

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

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

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

这是您的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递归Message@create而不仅仅是更新相同模型的属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM