2013-10-23 21 views
0

有人可以帮助我解决这个问题。如何加入这两个mysql表?

用户

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

友谊

+------+---------------------+ 
| uid | friend_id   | 
+------+---------------------+ 
| 1 | 2     | 
| 1 | 3     |  
| 2 | 4     | 
+------+---------------------+ 
  1. 假定当前用户ID为1
  2. 想获得当前用户的朋友的名字。(全部)
  3. 但是,此代码仅返回当前用户名对于找到的每个朋友。

对于上面的例子数据,输出为:John,John每行对应一行。

$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 

回答

2

你应该改变你的join条件。您要加入的用户ID和你想加入的朋友方:

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

总之,你得到2 jhon,因为你有2个朋友的jhon,但你得到的用户ID信息这些数据片段,你想要的朋友一边。

小提琴here

+0

仍然获得'约翰'两次。当前名称。注意:这是laravel 4语法。它使用'inner join'而不是'join'。我不知道区别。 – Pars

+1

它工作正常。我刚刚添加了一个小提琴证明如此。顺便说一句,'inner join'和'join'对于MySQL来说是一样的。 –

+1

哇,非常感谢你。你节省了我的时间。它正在工作......我的一个错字。在阅读您的查询之后。我修好了它。 – Pars

1

可能不是一个确切的回答你的问题,但你应该用雄辩的ORM做的事情,简单的,它可以是一些liket这样的:

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; 
} 
+0

据我所知ORM选择所有列,这是不好的。 ( 选择 * )。我只想得到一些特定的专栏。 – Pars

+1

你可以在Laravel Eloquent ORM上使用'get(['column1','column2'])''。它会写'select column1,column2 ...' –