簡體   English   中英

如何使用array_push在PHP / Laravel中通過數據庫查詢結果在foreach循環中添加鍵值對以標記返回的每一行?

[英]How can I use array_push to add a key value pair in a foreach loop through database query results in PHP/Laravel to flag each row returned?

我有一個函數,可以在單擊“顯示帖子”按鈕時檢索該帖子的所有評論。 然后使用Javascript顯示注釋,而我要執行的操作是向數組添加鍵值對,這將告訴我的JavaScript注釋所有者是否為登錄用戶,從而允許我添加編輯和刪除操作按鈕僅指向該用戶的帖子。

這可能是比較的最佳方法,但也可能不是最好的方法,但這是我在無限的經驗中積累的一種方法,因此我可以使用javascript顯示注釋並允許編輯/刪除注釋。 我知道我可以在數據庫表中添加一列my_posts並將其保留為空,然后使用array_push向該字段添加適當的值,但是我在這里嘗試過的方法可行嗎?

我的功能在這里:

public function postGetComments(Request $request) {
     $post = $request['postid'];
     $comments = DB::table('comments')
             ->join('users', 'users.id', '=', 'comments.user_id')
             ->select('comments.*', 'users.username')
             ->where('post_id', '=', $post)
             ->orderby('created_at', 'desc')
             ->get()
             ;
     foreach ($comments->get() as $comment) {
                $user = Auth::user();
                if ($user->id == $comment->user_id) {
                    $comment['my_post'] = 'true';
                } else {
                    $comment['my_post'] = 'false';
                }
     }
     return response()->json(['commentsForPost' => $comments]); 
}

我收到一個錯誤,因為我的foreach循環最后存在問題。 沒有此循環,查詢將檢索並按設計顯示所有注釋。 我是Laravel的新手(使用5.2),我想知道我在嘗試按下鍵my_post時做錯了什么,將comment.user_id與user.id進行比較,並在適當時添加值true / false數組? 謝謝!

您已經在$ comments查詢上運行了get()方法。 將您的foreach循環更改為此

foreach ($comments as $comment) {
                $user = Auth::user();
                if ($user->id == $comment->user_id) {
                    $comment['my_post'] = 'true';
                } else {
                    $comment['my_post'] = 'false';
                }
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM