Laravel 4:在索引视图中获取用户名而不是id,多对多关系

Laravel 4:在索引视图中获取用户名而不是id,多对多关系,laravel,orm,laravel-4,many-to-many,eloquent,Laravel,Orm,Laravel 4,Many To Many,Eloquent,我有一个friend_users表,在其中存储来自用户的用户id。现在我想知道谁是我的朋友,但我不知道如何使用eloquent访问用户的用户名 索引视图: @foreach($friend_users as $friend_user) <tr> <td>{{ $friend_user->friend_user_id }}</td> <td>{{ $friend_user->user->use

我有一个friend_users表,在其中存储来自用户的用户id。现在我想知道谁是我的朋友,但我不知道如何使用eloquent访问用户的用户名

索引视图:

@foreach($friend_users as $friend_user)
    <tr>
       <td>{{ $friend_user->friend_user_id }}</td>  
       <td>{{ $friend_user->user->user_username }}</td>
       <td>{{ $friend_user->friend->user_username }}</td>
    </tr>
@endforeach
用户模型:

public function users(){
        return $this->belongsToMany('User', 'friend_users', 'friend_id', 'user_id');
    }
public function friend() 
{ 
    return $this->belongsTo('User', 'friend_id'); 
}

public function user() 
{ 
    return $this->belongsTo('User', 'user_id'); 
}
FriendUser模型:

public function users(){
        return $this->belongsToMany('User', 'friend_users', 'friend_id', 'user_id');
    }
public function friend() 
{ 
    return $this->belongsTo('User', 'friend_id'); 
}

public function user() 
{ 
    return $this->belongsTo('User', 'user_id'); 
}

假设您在
FriendUser
模型中设置了这些关系

public function user() { return $this->belongsTo('User'); }
public function friend() { return $this->belongsTo('User', 'friend_id'); }
您可以立即加载您的用户模型(在控制器中):

在你看来:

@foreach($friend_users as $friend_user)
    <tr>
        // the user info
        <td>{{ $friend_user->user->id}}</td> 
        <td>{{ $friend_user->user->name}}</td>
        // the friend info
        <td>{{ $friend_user->friend->id }}</td>  
        <td>{{ $friend_user->friend->name }}</td>
    </tr>
@endforeach
@foreach($friend\u用户作为$friend\u用户)
//用户信息
{{$friend\u user->user->id}
{{$friend\u user->user->name}
//朋友信息
{{$friend\u user->friend->id}
{{$friend\u user->friend->name}
@endforeach
根据它的声音,这对你的目的来说是足够的,但是如果UsSeriID和FuffelID可以互换,你可能想考虑一个<代码>多对多< <代码> >关系。


感谢这一帮助,我用正确的代码更新了我的问题。在我的示例中,我不必更改控制器中的索引操作。