繁体   English   中英

从 Laravel 中的多对多关系中获取 Auth 用户的特定数据

[英]Fetch specific data for Auth user from Many to Many Relationship in Laravel

如何为 Laravel 多对多关系中的特定经过身份验证的用户获取数据? 我有一个页面,它将显示来自所有社区的所有最新线程。 但是,我想确保它只会显示来自当前登录用户所属社区的线程。 (我不确定我是否有道理)

用户.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()->user()帮助程序 function 并获取如下社区:

$communities = auth()->user()->communities;

但是你需要那些社区的线程,所以我们必须添加更多的逻辑,我们获取你关注的那些社区的 ID,然后检索这些社区包含的所有线程,然后在最后执行你需要的任何查询。

$communityIds = auth()->user()->communities->pluck('id');
$threads = Thread::whereIn('community_id', $communityIds)->latest()->paginate(20);

我没有测试这段代码,因为我没有相同的结构,所以你可能需要调试一两件事来修复查询,但理论上它应该与你的结构完全匹配。

您可以使用 auth 来访问经过身份验证的用户,有两种使用方法,一种是直接使用 auth,另一种是使用 Auth Facade:

  1. 直接地

    $threads = auth()->users()->threads()

  2. 正面

    $threads = Auth::user()->threads()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM