【问题标题】:How to join these two mysql tables?如何连接这两个mysql表?
【发布时间】:2013-10-23 20:04:14
【问题描述】:

谁能帮我解决这个问题。

用户

+------+---------------------+  
| id   | name                |  
+------+---------------------+  
| 1    | John                |  
| 2    | Jade                |    
| 3    | Robbert             |  
| 4    | Steve               |
+------+---------------------+

友谊

+------+---------------------+  
| uid  | friend_id           |  
+------+---------------------+  
| 1    | 2                   |  
| 1    | 3                   |    
| 2    | 4                   |  
+------+---------------------+
  1. 假设当前用户 ID 为 1。
  2. 想获取当前用户好友的姓名。(全部)
  3. 但此代码只返回它找到的每个朋友的当前用户名

对于上述示例数据,输出为:JohnJohn 每行各一个。

$friends = DB::table('users')
->join('friendship', function($join)
{
    $join->on('users.id', '=', 'friendship.uid');
})
->where('friendship.blocked', '=', '0' )
->where('users.id', '=', '1' )
->get();

SQL 代码以上:

select * from `users`
    inner join `friendship` 
        on `users`.`id` = `friendship`.`uid` 
where `users`.`id` = 1

【问题讨论】:

    标签: mysql sql laravel laravel-4


    【解决方案1】:

    您应该更改您的join 条件。您正在使用用户 ID 加入,并且您想在朋友方加入:

    select name from users
    join friendship on users.id = friendship.friend_id 
    where friendship.uid = 1
    

    简而言之,您将获得 2 个 jhon,因为您有 jhon 的 2 个朋友,但您获得了这些数据的用户 ID 信息,并且您想要朋友方面。

    小提琴here.

    【讨论】:

    • 仍然得到John 两次。当前名称。注意:这是 laravel 4 语法。它使用inner join 而不是join。我不知道有什么区别。
    • 它工作正常。我刚刚添加了一个小提琴来证明这一点。顺便说一句,inner joinjoin 对于 MySQL 来说是一样的。
    • 哇,非常感谢。你节省了我的时间。它正在工作......我的一个错字。阅读您的查询后。我修好了。
    【解决方案2】:

    可能不是您问题的确切答案,但您应该使用 Eloquent ORM 来做简单的事情,它可以是这样的:

    class User extends Eloquent {
    
        public function friends()
        {
            return $this->hasMany('friendship', 'uid');
        }
    
    } 
    
    class Friendship extends Eloquent {
    
        public function user($query)
        {
            return $this->belongsTo('User', 'friend_id');
        }
    
        public function scopeBlocked($query)
        {
            return $query->where('blocked', '=', '0');
        }
    
        public function scopeNotBlocked($query)
        {
            return $query->where('blocked', '=', '1');
        }
    
    } 
    

    那么你只需要使用它:

    $user = User::find(1);
    $friends = $user->friends()->notBlocked()->get();
    
    foreach($friends as $friend)
    {
        echo $friend->user->name;
    }
    

    【讨论】:

    • 据我所知,ORM 会选择所有列,这并不好。 ( 选择 * )。我只想获取一些特定的列。
    • 你可以在 Laravel Eloquent ORM 上使用 get(['column1', 'column2'])。它会写select column1, column2 ...
    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 2011-04-27
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2013-08-10
    相关资源
    最近更新 更多