【发布时间】:2015-08-23 12:12:49
【问题描述】:
我有一个用户模型和一个朋友模型。在用户模型中我有
public function friends(){
return $this->hasMany('App\FacebookModels\Friend' ,'user_id');
}
在朋友模型中我有
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();
});
【问题讨论】:
标签: eloquent laravel-5.1