get()方法不适用于雄辩的关系Laravel 5

时间:2015-08-23 12:12:50

标签: eloquent laravel-5.1

我有一个用户模型和一个朋友模型。在用户模型中我有

public function friends(){
        return $this->hasMany('App\FacebookModels\Friend' ,'user_id');
    }

在Friend模型中我有

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

我想检索用户的关注者,这就是我正在尝试的

    public function listFollowers($id,$name){

//user_id = 1 and there are two rows in table friends for user_id 1
            $user_id = $_SERVER['REQUEST_URI'];
            $user_id =  preg_replace("/[^0-9]/","",$user_id);
            $followers = Friend::where('user_id',$user_id)->get();
            foreach($followers->user as $user){
                echo $user->name;
            }
        }

但是我收到以下错误。

ErrorException in FacebookPagesController.php line 65:
Undefined property: Illuminate\Database\Eloquent\Collection::$user

行号65

foreach($followers->user as $user)

但是当我将get()更改为first()时 我收到以下错误

ErrorException in FacebookPagesController.php line 66:
Trying to get property of non-object

第66行是

echo $user->name;

但是,这适用于first()

echo $followers->user->name;

我无法理解这个的区别以及为什么这不起作用。如果你能解释一下这对大多数人来说都是好的。 这是我的friends table

Schema::create('friends', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('follower')->unsinged();
            $table->timestamps();
        });

这是users table

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });

1 个答案:

答案 0 :(得分:1)

first()会返回model个实例,get()会返回collection个模型。

因此,如果您想使用first(),则应使用getAttribute方法从$user获取属性/属性。

示例:

$name = $user->getAttribute('name');