【问题标题】:Extraction of data from database by criteria with Laravel使用 Laravel 通过标准从数据库中提取数据
【发布时间】:2016-07-26 10:30:21
【问题描述】:

您好,我尝试编写一些查询,希望通过相关标准从帐户中提取电子邮件。因此,例如,如果我想按城市发送电子邮件,我可以选择城市并将电子邮件发送给这个城市的人,但如果我不选择任何城市,它不应该识别这个并发送给所有人。

我的问题有没有按标准从数据库中提取数据的最佳方法?我应该写一个查询还是最好的方法是什么?

【问题讨论】:

  • 所有输入都是可选的,所以如果管理员没有选择任何输入,那么这应该返回数据库中的所有电子邮件,但如果他选择例如城市,那么这应该缩小到这个城市

标签: php laravel filter


【解决方案1】:

我不知道你到底在做什么,但基于对 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();

我相当肯定,这个示例代码的至少一部分从根本上是错误的,但从根本上说,它对于您想要做的事情也更加合乎逻辑和清晰。

【讨论】:

  • 我尝试这样做,但这样无法正确地从数据库中获取数据。例如,如果我选择 city=new york 和 accoutpremium=true,那么我有所有带有 city=new york 的电子邮件,但我还有其他带有 accout=premium 的电子邮件,其中人们来自其他城市,但他们只是添加到数组中,因为他们有溢价跨度>
  • 您需要获取它发送的原始查询。看起来下面的 SO 答案涵盖了这个:stackoverflow.com/a/18236656/49478
  • 所以您想要的查询类似于SELECT * FROM accounts WHERE location_id = "New York City" AND is_premium = 1 但相反,您得到的结果表明正在执行的查询更像SELECT * FROM accounts WHERE location_id = "New York City" OR is_premium = 1,因此不会在两个条件都为真的情况下获得结果,你得到的结果是任何一个条件都为真,对吧?
  • 最好的感谢来自接受的答案和关于具体解决您的问题的反馈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 2020-09-23
  • 2012-01-29
  • 1970-01-01
相关资源
最近更新 更多