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

时间:2014-08-20 14:09:21

标签: laravel orm laravel-4 many-to-many eloquent

我有一个friend_users表,我从用户那里存储user_id。现在我想看看谁是我的朋友,但我不知道如何使用eloquent访问user_username。

索引视图:

@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 index()
    {
        $friend_users = FriendUser::all();

        return View::make('friend_users.index')
            ->with('friend_users', $friend_users);
    }

用户模型:

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

FriendUser模型:

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

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

1 个答案:

答案 0 :(得分:1)

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

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

您可以急切加载您的用户模型(在您的控制器中):

$friend_users = FriendUser::with('user', 'friend')->where('user_id', $yourUserId);

return View::make('friend_users.index', array('friend_users', $friend_users));

在你看来:

@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

听起来,这应该足以满足您的目的,但如果user_id和friend_id可以互换,您可能需要考虑many to many关系。

http://laravel.com/docs/eloquent#many-to-many