php - Laravel retrieve data with condition from many-to-many condition
问题描述
I have three tables:
email_accounts (list of business emails)
-------------
id
email
sender_name
users
------
id
name
email
email_accounts_users
--------------------
email_account_id
user_id
And the eloquent relationship is declared as:
User
------
public function emailAccounts()
{
return $this->belongsToMany(EmailAccount::class,'email_accounts_users');
}
EmailAccount
------------
public function users()
{
return $this->belongsToMany(User::class,'email_accounts_users');
}
I am trying to fetch rows from email_accounts
that belongs to current user.
This could be correctly fetched as:
$email_acc = \DB::table('email_accounts')
->join('email_accounts_users', 'email_accounts_users.email_account_id', 'email_accounts.id')
->join('users', 'users.id', 'email_accounts_users.user_id')
->select('email_accounts.*')
->where('user_id',auth()->user()->id)
->get();
dd($email_acc);
However, I am trying to get with laravel eloquent model. So, I tried as follows:
$email_acc = EmailAccount::with(['users' => function(){
$query->where('users_id',auth()->user()->id)
}])->get();
dd($email_acc);
However, its returning all the emails from email_accounts
, rather its filtering the data from users table and sending only the currently logged in user
. from users table.
However, my requirement is to fetch emails form email_accounts
that belong to currently logged in users.
Like
解决方案
Specify foreign keys as follows
public function emailAccounts()
{
return $this->belongsToMany(EmailAccount::class,'email_accounts_users', 'id', 'email_account_id' );
}
EmailAccount
------------
public function users()
{
return $this->belongsToMany(User::class,'email_accounts_users', 'id', 'user_id');
}
推荐阅读
- r - R - dbWriteTable 在列名中使用大写字母
- amazon-web-services - 在 DynamoDb 中,Time To Live 删除是否计入写入容量
- apollo - 将嵌套对象写入本地 Apollo 缓存
- r - 如何以 10 分钟的步骤聚合数据
- http - netcat 在 http get 请求上不断超时
- python - strptime 在 docker 容器中运行时抛出错误
- php - 更新到 laravel 5.5 后 EventServiceProvider 无法正常工作
- angular - Angular 发布到 IIS 后未与 ASP.Net 通信
- r - 迭代/循环列表
- angular - 角度路由:一个奇怪的错误:无法读取 null 的属性“路径”