我想向在第二个表中激活选项但不确定如何操作的用户发送电子邮件 .
逻辑
-
从
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');
});
2 回答
这将有效:
你正在做的一切都是正确的,但你在
whereIn
子句中添加额外的数组 . 因为,pluck已经返回一个数组,所以不需要在whereIn
子句中再次添加[],所以,你的代码应该是
我希望你明白 .