2014-11-29 3 views
0

У меня есть две таблицы users и friends. Как я могу написать всех друзей пользователя с userID (1)? Какую связь я должен использовать?Laravel 4 отношения между таблицами пользователей и друзей

User.php

<?php 

use Illuminate\Auth\UserTrait; 
use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableTrait; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class User extends Eloquent implements UserInterface, RemindableInterface { 

    protected $fillable = array('email', 'username', 'password', 'password_temp', 'code', 'active', 'remember_token'); 



    use UserTrait, RemindableTrait; 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'users'; 
    public function friends() 
    { 
     return $this->belongsToMany('Friend'); 
    } 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array('password', 'remember_token'); 


} 

Friend.php

<?php 


class Friend extends Eloquent { 

    protected $fillable = array('friend_one', 'friend_two', 'status'); 




    protected $table = 'friends'; 
    public function users() { 

     return $this->belongsToMany('User'); 
     } 


} 

Контроллер

public function getFriendShow(){ 
     $cur_login = User::find(Auth::user()->id); 
     $friends = $cur_login->friends; 

     return View::make('profile.friends')->with('friends', $friends); 

    } 

friends.blade.php

 <ul> 
     @foreach($friends as $friend) 
     <li><a href="">{{ }}</a></li> 
     @endforeach 
    </ul> 

ответ

1

Изменить контроллер для

public function getFriendShow(){ 

     $id = Auth::user()->id; 
     $friends = Friend::where('userID','=', "4")->get(); 

     return View::make('profile.friends')->with('friends', $friends); 

    } 

Является ли это полезно?

+0

Как я могу написать всех друзей, использующих имя пользователя из таблицы пользователей? – oiuoiuiou

+0

В приведенном выше коде он захватывает всех друзей для текущего зарегистрированного пользователя. У вас было другое намерение? – Rafael

+0

Это будет записывать запись из таблицы друзей, где sh нравится: {"id": 26, "friend_one": 4, "friend_two": 4, "status": "1", "created_at": "2014-11 -29 16:37:22 "," updated_at ":" 2014-11-29 16:37:22 "}, и я хочу использовать имя пользователя пользователя, id которого 4 – oiuoiuiou

Смежные вопросы