【问题标题】:Laravel 5.5 How to get all models related to model?Laravel 5.5 如何获取与模型相关的所有模型?
【发布时间】:2018-05-31 02:06:24
【问题描述】:

我有与自己有关系的模型用户

public function subscription()
{
    return $this->belongsToMany('App\User', 'subscription', 'subscriber_id');
}

我为使用户相互订阅而制作的。我做了数据透视表 有 2 列(subscriber_id、user_id)。所以在用户个人资料上,我向所有用户展示了当前用户订阅的所有用户

$user = User::where('slug', $slug)->first();
$subscribed = $user->subscription;

这行得通。所以现在我不知道如何显示订阅该用户的所有用户?我尝试使用DB::table('subscription')->where('user_id', 1)->get();,但这并没有返回用户模型。我知道这是一个简单的解决方案,但我真的坚持这个......

【问题讨论】:

    标签: php mysql laravel pivot relationships


    【解决方案1】:

    您可以简单地遍历$subscribed 集合以获取所有用户对该用户的订阅。

    $user = User::where('slug', $slug)->first();
    $subscribed = $user->subscription;
    
    foreach ($subscribed as  $subscriber) {
    
        $subscriber->name;
    }
    

    【讨论】:

    • 然后我得到该用户订阅的所有用户,我已经拥有了。我需要所有订阅该个人资料的用户。
    • @MilePanic 您的问题不清楚。请多解释
    • 好的,所以在用户个人资料页面上,我想显示订阅他的所有用户,以及他订阅的所有用户。我写了如何制作个人资料订阅的用户列表$user->subscription,它返回个人资料订阅的所有用户的集合。现在我需要相反的 - 订阅该配置文件的所有用户的列表。我希望我现在对我的问题更清楚了。
    • 解决了。不管怎么说,多谢拉。 $query = DB::table('subscription')->where('user_id', 1)->pluck('subscriber_id')->toArray(); $subscribed = User::whereIn('id', $query)->paginate(10);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2018-10-12
    • 2018-07-11
    • 1970-01-01
    • 2015-09-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多