在我的应用程序中,我有一个通知表和一个用户表,一个通知可以属于许多用户,所以在我的通知类中,我有以下内容,
public function user()
{
return $this->belongsToMany('User');
}
在我的数据库中,我还有一个名为 notification_user
的表,它位于我的 notifications
表旁边。 notification_user
表具有以下行,
notification_id、user_id、is_read、created_at、updated_at
我正在运行以下代码来返回特定用户的通知,
$notifications = Notification::whereHas('user', function($q){
$q->where('user_id', '=', 101);
})->get();
我发现的问题是,这不会从我迫切需要的 notification_user
表中返回 is_read 属性!我尝试添加,
$notification->load('user')
,但这只是将用户数据添加为对象。
是否也可以获取关系表数据?
最佳答案
您需要在关系中添加一些额外的内容,以告诉 laravel 从数据透视表中提取额外的数据。 (不要忘记在您关系中的其他模型上也执行此操作)
public function user()
{
return $this->belongsToMany('User')->withPivot('is_read');
}
然后,您的模型上应该有一个带有 is_read
属性的 ->pivot
属性。 (例如:$notification->pivot->is_read)这在文档 http://laravel.com/docs/5.0/eloquent#working-with-pivot-tables 中有简要介绍。
如果你已经有了用户ID,只是为了让事情变得更简单,你不能直接使用它们之间的关系吗?
$user = User::find(101);
foreach($user->notifications as $notifications)
{
if ($notification->pivot->is_read === false)
{
// Notification is unread, lets do something
}
}
关于php - Laravel 4 从关系中收集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510638/