所以我在Laravel中与这些关系非常糟糕,我无法让我的一对多关系发挥作用。假设我有一个像这样的朋友系统:
表用户:
id | username | password
表朋友:
id | person1(int) | person2(int)
person1和person 2是表格中用户的ID
现在我有这两个模型:
class Friend extends Eloquent {
protected $table = 'friends';
public function friend_relations(){
return $this->belongsTo('User');
}
}
和
class User extends Eloquent {
protected $table = 'users';
}
现在我正在做的是,登录后,我想在主页上显示登录的人的ID。所以为了得到这个,我会让它像这样运行:
$friends = Friend::where('person1', $id)->get();
现在这将给我两个人的ID,现在我想获得属于该用户的用户名而不运行不必要的额外查询,所以我会使用一对多的关系。但是我似乎无法通过查询立即获取用户登录的朋友的姓名。
我尝试过类似的事情:
$friends = Friend::where('person1', $id)->friend_relations;
和
$friends = Friend::all()->friend_relations()->where('person1',$id)->get();
给了我:Call to undefined method friend_relations()
但这会给我一个错误:Undefined property friend_relations
。
我做错了什么?
答案 0 :(得分:2)
你的人际关系有点偏差,因为你可能会想到这个错误。
即使它可能看起来不像,但它属于许多关系,而您的datepart, date
表实际上是一个与您的friends
表相关联的数据透视表。
为了进一步简化这一点,您应该重命名users
表中的列,以便更清楚它是什么。 friends
和person1
非常模糊,只会让人感到困惑。话虽如此,我将假设两列是person2
和user_id
。如果您不想这样做,请假设我说friend_id
,我的意思是user_id
,而person1
会映射到您的friend_id
。
尽管如此,这成为一个相当简单的问题。将以下内容添加到person2
模型中。
User
现在,为了与朋友一起检索用户,您可以执行以下操作。
public function friends()
{
return $this->belongsToMany(User::class, 'friends', 'user_id', 'friend_id');
}
此外,您的$user = User::with('friends')->find($id);
$friends = $user->friends; // This will return a collectino of friends.
模型变得不必要,因此您可以随意删除它。
现在Friend
将成为$friends
对象的Collection
(您可以将其视为一种数组)。集合中将有0个,1个或多个User
个对象,因此尝试使用User
没有任何意义,因为它不知道$friends->date
的哪个User
该集合中的日期可以从中获取。
您需要循环访问它以访问每个用户的属性。
foreach($friends as $friend) {
echo 'Name: ' . $friend->name;
echo 'Date: ' . $friend->date;
}