[英]Laravel relationships get user emails
嘿,從我的網站向用戶發送多個通知,將用戶分配給團隊,然后將該團隊分配給通知表。
但是,當我執行SiteNotification::find(1)->notifications()
我得到了團隊的名稱,但是,我一直在尋找用戶模型以及與此相關的所有詳細信息。 有沒有一種簡單的方法可以使用Laravel雄辯的關系獲得此信息?
我的數據庫模型和口才模型如下:
數據庫表;
用戶
id | username | email
隊伍
id | name |
團隊成員
team_id | user_id
網站通知
site_notification_id | team_id
此處模型:
class SiteNotification extends Model {
public function notifications()
{
return $this->belongsToMany(Team::class, 'site_check_notifications', 'site_check_id', 'team_id');
}
}
更新:
我嘗試如下更新團隊模型;
class Team extends Model
{
public function users()
{
return $this->hasManyThrough(
User::class,
TeamMember::class,
'team_id',
'id'
);
}
}
但是,這在運行時會引發如下錯誤:
$site = Site::find(1);
foreach( $site->notifications as $notification) {
dd($notification->users);
}
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'team_members.id' in 'on clause' (SQL: select `users`.*, `team_members`.`team_id` from `users` inner join `team_members` on `team_members`.`id` = `users`.`id` where `team_members`.`team_id` = 4)
任何想法我在做什么錯?
我找到了一個解決方案,它意味着我不需要修改現有的數據庫結構,並且找到了可以使用的正確關系。
public function users()
{
return $this->belongsToMany(
User::class,
'team_members',
'team_id',
'user_id'
);
}
現在我可以做Site::find(1)->users->pluck('email')
您必須更改模型結構...這就是我要達到的目標...將其作為“有效的解決方案”,也許不是最好的!
首先是數據庫。 您應該有這些表,沒有必要
users => users table
teams => teams table
team_user => pivot table n:n
team_site_notification => pivot table n:n
site_notifications => notifications table
user_site_notification => pivot table n:n
然后創建相關的模型關系
public class User {
// [...]
public function teams() {
return $this->belongsToMany(Team::class)
}
public function notifications() {
return $this->belongsToMany(SiteNotification::class)
}
}
public class Team {
// [...]
public function users() {
return $this->belongsToMany(User::class)
}
public function notifications() {
return $this->belongsToMany(SiteNotification::class)
}
}
public class SiteNotification {
// [...]
public function teams() {
return $this->belongsToMany(Team::class)
}
public function users() {
return $this->belongsToMany(User::class)
}
}
在您的控制器中,當您創建SiteNotification
模型時,您還必須關聯用戶。 例如
public function store(Request $request) {
// Do your stuff
$team = Team::findOrFail($request->your_team_id);
$notification = Notification::create($data);
$notification->teams()->associate($request->your_team_id);
// Retrieve the users from the team... Maybe not everyone should receive a notification
$team->users()->whereIn('id', $user_ids)->get()->pluck('id')
$notification->users()->associate($ids);
}
當您要獲取用戶列表時,可以通過以下方式簡單地檢索關聯的用戶:
dd($notification->users);
// [ User:{id: 1, '...'}, User:{id: 2}, User:{id: 7} ]
希望這就是您要尋找的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.