首页 > 解决方案 > Laravel + Vue 循环一次特定 ID

问题描述

大家好,所以我打算列出我最近的聊天记录。问题是我只想循环相同的Id(例如Chatroom_id),在我的情况下它循环相同的Chatroom Id 5次,导致我检查一个数据库reciever_id是我的,结果是5,因此是5次它循环相同的聊天室 ID。我只想让它循环一次聊天室 ID

Laravel View // 我在哪里插入我的 vue 组件

 <!--- Message or online followers and followings -->
   <div id="messagesidebar" class="app-sidebar-userdetails">   
       <h6 class="sm text-white"> <i> Recent Chat </i> </h6>

           <div id="recentchat">
              <recentchat-component :user_id="{{ Auth::user()->id }}"></recentchat-component>
            </div>

          </div>
          <!-- /# Message or online followers and followings  -->
       </div>    

Vue 模板

  <div class="chats" v-for="recentchat in recentchats" v-bind:key="recentchat.id">

          {{ recentchat.chatroom_id}}


   </div>

Laravel 控制器

public function fetchrecentchat($user_id)
{
    $recentchat = Chat::Where('receiver_id', $user_id)
    ->orderBy('created_at', 'DESC')
    ->get();


    return ChatResource::collection($recentchat);
}

聊天资源

public function toArray($request)
{
    // return parent::toArray($request);
    return [
        'id' => $this->id,
        'message' => $this->message,
        'chatroom_id' => $this->chatroom_id,
        'user_id' => $this->user_id,
        'receiver_id' => $this->receiver_id,    
        'created_at' => $this->created_at->diffForHumans(),  
        'updated_at' => $this->updated_at,       
    ];
} 

告诉我您是否需要查看我没有在上面添加的代码,非常感谢你们!

更新

Vue 脚本

<script>
export default {
    props: [ 'user_id' ],
    data() {
        return {
        recentchats: [],
        recentchat: {
           id: '',
            chatroom_id: '',
             user_id: '',
              receiver_id: '',
               created_at: '',
                updated_at: '',
        }
     }

    },
    created() {
        this.fetchchatrooms();
    },
    methods: {
         fetchchatrooms(){
             fetch('/api/fetchrecentchat/' +this.user_id)
             .then(res => res.json())
             .then(res => {
                 console.log(res);
                 this.recentchats = res.data
             });
         }
    },
    mounted() {
        console.log('Recent Chat mounted.')
    }
}

标签: laravelvue.js

解决方案


推荐阅读