【问题标题】:Laravel Many To Many Method IssueLaravel 多对多方法问题
【发布时间】:2016-09-23 01:19:01
【问题描述】:

我在模型用户和通知之间有多对多的关系。

用户模型:

public function notifications()
{
    return $this->belongsToMany('Yeayurdev\Models\Notification', 'notifications_user', 'user_id', 'notification_id')
        ->withPivot('notifier');
}

通知模型:

public function user()
{
    return $this->belongsToMany('Yeayurdev\Models\User', 'notifications_user', 'notification_id', 'user_id');
}

数据透视表:

ID     USER_ID     NOTIFICATION_ID
1         2               1

在我看来,我为这样的用户检索了所有通知的列表。

@foreach (Auth::user()->notifications as $notification)
   {{ $notification->user->username }}
@endforeach

问题是,当我尝试使用该通知获取用户的用户名时,我收到错误 Undefined property: Illuminate\Database\Eloquent\Collection::$username。 “用户名”是我的用户表上的列,它只是一个字符串。我看不出哪里出错了,因为如果我只执行“$notificatin->user”,它就会给我集合。

谢谢!

【问题讨论】:

  • 你试过用括号{{ $notification->user()->username }}吗?
  • 您能否将$notification->user 的内容添加到您的问题中。谢谢。

标签: laravel laravel-5.2


【解决方案1】:

正如您所说,这种关系是多对多的,因此 $notification->user 在您的情况下返回的是用户模型的集合,而不是单个用户。如果您只需要第一个用户,那么就这样做

{{ $notification->user()->first()->username }}

如果您需要为每个通知打印出所有用户,那么您将需要一个循环来遍历所有用户。

@foreach (Auth::user()->notifications as $notification)
    @foreach($notification->user as $notificationUser)
        {{ $notificationUser->username }}
    @endforeach
@endforeach

我建议将 user() 关系重命名为 users() 以避免将来混淆。

【讨论】:

  • 是的,我刚刚想通了。当我执行 $notification->user 并查看输出时,应该首先注意到。谢谢!
猜你喜欢
  • 2021-07-22
  • 2014-11-11
  • 2015-09-14
  • 1970-01-01
  • 2019-05-06
  • 2014-05-24
  • 2020-02-29
  • 2019-11-25
  • 1970-01-01
相关资源
最近更新 更多