您好我试着写一些查询,我想根据相关标准从帐户中提取电子邮件。因此,例如,如果我想通过城市发送电子邮件,我可以选择城市并发送电子邮件给这个城市的人,但如果我不选择任何城市,它不应该认识到这一点,并发送给所有人。
我的问题是否有从标准中提取数据的最佳方法?我应该写一个查询或者最好的方法是什么?
答案 0 :(得分:0)
我不知道你在做什么,但基于对Laravel的基本理解以及你试图用不同的“标志”或“标准”做什么,继续添加是否有意义根据每个条件到主集合,然后在主集合的查询属性全部添加后获取电子邮件地址。例如:
// Start with your Account, ordered by ID:
$accounts = Account::orderBy('id');
// if a city ID is provided, add this to the "where" section of the main collection:
if($this->city_id !== NULL) {
$accounts->where('location_id', $this->city_id);
}
// if an Account Type is provided, add this to the "where" section of the main collection:
if ($this->account_type !== NULL) {
$accounts->where('type_id', $this->account_type);
}
// if Premium Only is set, add this to the "where" section of the main collection:
if ($this->only_premium == TRUE) {
$accounts->where('is_premium', $this->only_premium);
}
// if Free Only is set, add this to the "where" section of the main collection:
if ($this->only_free == TRUE) {
$accounts->where('is_premium', $this->only_free);
}
/* For those last two, it's a bit confusing whether only_free and only_premium are mutually exclusive,
so maybe consider having one property that toggles between Free/Premium
(assuming it can't be both but must be one or the other). */
// Finally, pull the emails (the "plucking" off of the final $accounts collection variable:
$emailAccounts = $accounts->get()->pluck('email')->toArray();
我相当确定这个示例代码中至少有一部分是根本错误的,但是对于你想要做的事情来说,它也从根本上更符合逻辑和清晰。