如何在 Laravel 多对多关系中获取特定经过身份验证的用户的数据?我有一个页面,它将显示所有社区的所有最新主题。但是,我想确保它只显示当前登录用户所属社区的线程。 (不知道我说的有没有道理)
User.php
public function communities()
{
return $this->belongsToMany(Community::class)->withTimestamps();
}
public function threads()
{
return $this->hasMany(Thread::class);
}
社区.php
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
public function threads()
{
return $this->hasMany(Thread::class);
}
线程.php
public function user()
{
return $this->belongsTo(User::class, 'author_id', 'id');
}
public function community()
{
return $this->belongsTo(Community::class);
}
这就是我在没有登录用户的情况下获取数据的方法。
$threads = Thread::with(['user', 'community'])->orderBy('created_at')->paginate(20);
我想要实现的是从登录用户所属的社区获取最新的线程。
您可以使用 auth 来访问经过身份验证的用户,
有两种使用方法,第一种是直接使用 auth,第二种是使用 Auth Facade:
-
Directly
$threads = auth()->users()->threads()
-
Facade
$threads = Auth::user()->threads()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)