我想向第二个表中具有激活选项但不确定如何激活的用户发送电子邮件。
mailings
表中获取所有用户ID latest_blog
列是否设置为on
$latest_blog = Mailing::where('latest_blog', 'on')->pluck('user_id');
$users = User::whereIn('id', [$latest_blog])->get();
foreach($users as $user){
Mail::to($user->email)->send(new BlogUpdates($user, $post));
}
dd($latest_blog);
返回
Collection {#1705 ▼
#items: array:5 [▼
0 => 41
1 => 51
2 => 42
3 => 60
4 => 61
]
}
dd($users);
仅返回1个用户,而所有用户的latest_blog
列均设置为on
。因此基本上应该返回5个用户,而不是1个。
Collection {#1758 ▼
#items: array:1 [▼
0 => User {#1756 ▶}
]
}
有什么主意吗?
Mailing model
protected $fillable = [
'user_id', 'interests', 'security', 'latest_projects', 'latest_blog'
];
public function user()
{
return $this->belongsTo(User::class);
}
User model
protected $fillable = [
'name', 'username', 'email', 'password', 'points', 'google2fa_secret'
];
public function mails()
{
return $this->hasOne(Mailing::class);
}
Mailing Schema
Schema::create('mailings', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable()->unique();
$table->string('interests')->default('on');
$table->string('security')->default('on');
$table->string('latest_projects')->default('on');
$table->string('latest_blog')->default('on');
$table->timestamps();
});
Schema::table('mailings', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
答案 0 :(得分:2)
您所做的一切都是正确的,但是您在whereIn
子句中添加了额外的数组。由于pluck已返回数组,因此无需在whereIn
子句中再次添加[],
您的代码应为
$latest_blog = Mailing::where('latest_blog', 'on')->pluck('user_id');
$users = User::whereIn('id', $latest_blog)->get();
foreach($users as $user){
Mail::to($user->email)->send(new BlogUpdates($user, $post));
}
希望您能理解
答案 1 :(得分:1)
这将起作用:
$latest_blog = Mailing::where('latest_blog', 'on')->get()->pluck('user_id');
// dd($latest_blog);
$users = User::whereIn('id', $latest_blog->toArray())->get();
foreach($users as $user){
Mail::to($user->email)->send(new BlogUpdates($user, $post));
}