我有四个表四个雄辩的模型;用户,个人资料,Habs,粉丝。 我正在尝试检索用户关注者的所有用户帖子和用户帖子。 我的桌子看起来像这样;
哈布斯
用户
配置文件
关注
的updated_at
我在模特中建立了关系。如何使用Eloquent选择用户发布的用户帖子和帖子。
答案 0 :(得分:1)
嗯,我想你可以从这样的事情开始:
class Users extends Eloquent {
protected $table = 'users';
public function profile()
{
return $this->belongsTo('Profile');
}
public function followers()
{
return $this->hasMany('Follower', 'follower_id', 'id');
}
public function following()
{
return $this->hasMany('Follower', 'following_id', 'id');
}
}
class Hab extends Eloquent {
protected $table = 'habs';
public function user()
{
return $this->belongsTo('User');
}
}
class Follower extends Eloquent {
protected $table = 'followers';
}
class Profile extends Eloquent {
protected $table = 'profiles';
}
你应该能够:
通常选择用户
$user = User::find(1);
得到它的Habs
$habs = $user->habs;
获得粉丝
$followers = $user->followers;
让谁跟随他/她
$following = $user->following;
获取所有追随者的habs
foreach($user->followers as $follower)
{
$followerEmail = $follower->email;
$followerName = $follower->profile->name;
$followerHabs = $follower->habs;
}
从他/她关注的人那里获取所有habs
foreach($user->following as $following)
{
$followingEmail = $following->email;
$followingName = $following->profile->name;
$followingHabs = $following->habs;
}
答案 1 :(得分:1)
这是HasManyThrough
的一个很好的用例。它允许您查询远程关系。
https://laravel.com/docs/5.5/eloquent-relationships#has-many-through
答案 2 :(得分:0)
您只需要在用户模型上设置关系
// Users Model
public function followings()
{
return $this->belongsToMany(
'Users',
'followers', // Assuming this is the table name
'follower_id',
'following_id'
);
}
public function posts()
{
return $this->hasMany('Habs');
}
然后获取用户的帖子
$posts = User::with('posts')->find(1)->posts;
并获得以下用户的帖子
$following_users = User::find(1)->followings()->with('posts')->get();