【问题标题】:Laravel Eloquent select from one table and join first row if there's a match from another tableLaravel Eloquent 从一个表中选择并在另一个表中有匹配项时加入第一行
【发布时间】:2020-08-25 11:06:54
【问题描述】:

我有两张桌子

+----+------------+------------+
| id | first_name | date       |
+----+------------+------------+
| 1  | Bob        | 01/01/2019 |
+----+------------+------------+
| 2  | June       | 01/05/2019 |
+----+------------+------------+

+----+--------+---------+------------+
| id | userID | comment | date       |
+----+--------+---------+------------+
| 1  | 1      | Hello   | 02/01/2019 |
+----+--------+---------+------------+
| 2  | 1      | Again   | 02/02/2019 |
+----+--------+---------+------------+
| 3  | 2      | Howdy   | 02/03/2019 |
+----+--------+---------+------------+

我想获取所有名字为 Bob 的用户的结果,并将最新的评论附加到该结果。

我可以的

$users = SELECT * FROM Users WHERE id = 1

然后

foreach($users as $user){
    $comment = Comment::where("userID", $user->id)->first();
    if($comment != null){
        $user->comments = $comment->$comment;
    }
}

但是如果 $users 中有很多结果会很慢

【问题讨论】:

  • 我的回答对您的问题有帮助吗?否则我很高兴尝试修复它:)

标签: php mysql sql laravel eloquent


【解决方案1】:

使用 Eager loading 和自定义查询:

User::with(['comments' => function($query){
  $query->latest();
}])->where('first_name','bob')->get();

【讨论】:

    【解决方案2】:

    额外的关系可以解决问题。

    public function latestComment()
    {
        return $this->hasOne(Comment::class)->latest('date');
    }
    

    现在您可以通过$user->latestComment 访问它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多