首页 > 解决方案 > 不会显示数据库 laravel 中的所有好友

问题描述

我在数据库中创建了一个朋友表,其中包括 requesteeid(请求成为朋友的用户的 id)、inboundid(朋友请求要去的用户的 id)和已批准的列,当设置为 false = 挂起,当设置为 true = 接受时,目前似乎只有一个用户,当我回显 $rowsget 时,当我尝试循环时,查询的所有行在入站或出站中都将显示配置文件 ID我只得到一个,即添加该用户(inboundee)为朋友的最新用户。我已经花了几个小时,非常感谢任何帮助!

数据库搜索

<?php
$rowsget = DB::table('friends')->where('requesteeid', $uid)- 
>orWhere('inboundid', $uid)->where('approved', true)->get();

if(count($rowsget) > 0){
    foreach($rowsget as $get) {
        $getrequestee = $get->requesteeid;
        $getinbound = $get->inboundid;
 }
    $rowfetchfriend = DB::table('users')->where('id', $getrequestee)- 
  >orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);


?>

循环浏览个人资料的朋友

   <?php
   foreach($rowfetchfriend as $loop) {
        if($loop->id != $uid) { //make sure own user isnt displayed
            echo $loop->username; // echo all usernames that are friends
        }
    }
    ?>

标签: phpdatabaselaravel

解决方案


我敢打赌,当您像 yiu 那样使用它时,您的 SQL 一定会出错。提示:您设置 no () 来分隔您的 (gimme all n where (x is something or y is some other) and z is true)。您在没有 () 的情况下执行所有操作,因此它将搜索 (x is something) 或 y is some other 而 z 为 true,因此将找到所有行,其中 z 为 true 而 y 是 someother,因此此结果是错误的。

尝试

$rowsget = DB::table('friends')
->where(function (Builder $query) use ($uid) {
  $query->where('requesteeid', $uid)
    ->orWhere('inboundid', $uid);
  })
->where('approved', true)
->get();

您还可以使用以下方法获取 SQL 查询

$rowsget = DB::table('friends')
->where(function (Builder $query) use ($uid) {
  $query->where('requesteeid', $uid)
    ->orWhere('inboundid', $uid);
  })
->where('approved', true)
->toSql();

将您的代码更改为:

$rowfetchfriend = [];
if(count($rowsget) > 0){
    foreach($rowsget as $get) {
        $getrequestee = $get->requesteeid;
        $getinbound = $get->inboundid;  
        $rowfetchfriend += DB::table('users')->where('id', $getrequestee)- 
  >orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);
}

您的右括号是错误的,您必须将每个循环的结果相加。我会执行另一个 sql,在那里我以我想要的方式得到我的结果,并且不会为此触发 2 个查询(查找“连接”)。


推荐阅读