【问题标题】:Will not show all friends in database laravel不会显示数据库 laravel 中的所有好友
【发布时间】:2019-01-04 09:01:42
【问题描述】:

我在数据库中创建了一个朋友表,其中包括 requesteeid(请求成为朋友的用户的 id)、inboundid(朋友请求要去的用户的 id)和已批准的列当设置 false = 待处理并且设置 true = 接受时,目前似乎只有一个用户,当我回显 $rowsget 时,当我尝试和尽管我只得到一个,但循环遍历,即已将该用户(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
        }
    }
    ?>

【问题讨论】:

  • 您确定您的查询需要-&gt;where('approved', true) 吗?批准是那些已经批准的朋友,他们不能入站或出站
  • 为什么要在问题标题中包含业务逻辑?没有人会通过阅读标题知道这个主题是关于什么的,因为friends 对于不了解您项目的人来说毫无意义......
  • @Xatenev 抱歉,我想的不对,我应该用行或类似的东西替换它
  • @OleksandrPobuta 如果我回显 $rowsget,则查询不是问题,行完美回显,当我尝试循环浏览用户信息时,我收到一条错误消息。

标签: php database laravel


【解决方案1】:

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

试试

$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 个查询(查找“joins”)。

【讨论】:

  • 嗨,我刚刚尝试过它没有用,如果我回显 $rowsget,查询不是问题,行完美回显,当我尝试遍历用户信息时,我得到一个错误信息。
  • 好的,我需要两件事:你的数据库的结构和确切的错误信息,所以请编辑你的帖子和这个信息
  • Schema::create('friends', function (Blueprint $table) { $table->increments('id'); $table->integer('requesteeid'); $table-> integer('inboundid'); $table->boolean('approved')->default(false); $table->timestamps(); });
  • 我没有收到任何错误消息,它只是没有遍历我的所有行
  • 是的,它没有。我在你的第一篇文章中看到了你的代码,很明显,你循环遍历 rowsget 并且对于每一行,你覆盖你的变量 getrequestee 。之后,您向 id 为 requesteeid 或 getinbound 的用户发出一个请求,因此您将获得最多 2 个结果;)
猜你喜欢
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
  • 2020-06-29
  • 2015-04-04
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 2017-06-01
相关资源
最近更新 更多