Laravel 4用户和朋友表之间的关系

时间:2014-11-29 19:33:47

标签: php laravel-4

我有两张表usersfriends。如何用userID(1)写出所有用户的朋友? 我应该使用哪种关系?

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 个答案:

答案 0 :(得分:1)

将控制器更改为

public function getFriendShow(){

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

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

    }

这有用吗?