如何为每个发件人获取最后插入的值?

时间:2016-08-08 13:28:45

标签: php laravel laravel-5.2

我知道您可以使用此$insertedId = $user->id;获取最后插入的ID但我尝试在每个发送数据的发件人的视图中获取最后插入的值。就像收件箱一样,它始终显示发件人发送的最后一条消息。我怎样才能在我看来展示这个?

这是发送消息的 POST

public function postMessage(Request $request)
{
    $this->validate($request,
    [
        'recipient' => 'required',
        'message' => 'required|max: 2000',
    ]);

    $message = new Message();

    $message->message_content = $request->message;

    $message->save();

    $user = Auth::user();

    foreach($request->recipient as $recipientId)
    {
        $message->users()->sync([ $recipientId => ['sender_id' => $user->id]],false );
    }

    return redirect()->back();
}

检索值。到目前为止我在这里做的只是检索所有用户的消息。仍然不知道如何插入最后一个。任何帮助我怎样才能做到这一点?

public function getMessage()
{
    $recipientLists = DB::table('users')->where('id', '!=', Auth::id())->get();

    $messageResult = DB::table('message_user')->select('messages.message_content', 'users.username', 'messages.id')
        ->join('users', 'users.id', '=', 'message_user.sender_id')
        ->join('messages', 'messages.id', '=', 'message_user.message_id')
        ->where('user_id', '=', Auth::id())
        ->where('sender_id', '=')->get();

    return view ('message.create')->with('recipientLists', $recipientLists)->with('messageResult', $messageResult);
}

迁移(数据透视表)

public function up()
{
    Schema::create('message_user', function (Blueprint $table)
    {
        $table->increments('id');

        $table->integer('message_id')->unsigned();
        $table->foreign('message_id')->references('id')->on('messages')->onDelete('cascade');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        $table->unsignedInteger('sender_id')->nullable();
        $table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');

        $table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('dateModified')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
    });
}

0 个答案:

没有答案