Laravel-如果查询为空则返回不同的查询

时间:2018-09-05 23:38:56

标签: php mysql laravel

我编写的查询有时可能包含空列,即使广告系列表中有值,该列也会导致查询返回空数组。这是因为如果列值为空,则查询无法生成join。我正在尝试编写一条if语句以返回campaign,即使其值为空,但仍返回一个空数组。如果我在if语句中运行查询,它将返回我要查找的内容,只是无法触发if语句。

  public function getCampaigns(Request $request)
  {
    $authUser = auth()->user();
    $business = $authUser['business_id'];
    $query = campaigns::join('offers', 'campaigns.offer_id', '=', 'offers.id')
            ->join('conditionals', 'campaigns.conditional_id', '=', 'conditionals.id')
            ->join('triggers', 'campaigns.offer_id', '=', 'triggers.id')
            ->select('campaigns.*',
            'triggers.name AS trigger_name',
            'offers.name AS offer_name',
            'offers.reward_amount as offer_reward_amount',
            'offers.plaid_category_id as offer_plaid_id',
            'conditionals.dollars_min',
            'conditionals.dollars_max',
            'conditionals.dollars_more',
            'conditionals.xDays as days_since_last_purchase',
            'conditionals.xDate as date_since_last_purchase',
            'conditionals.xPercent as percentage_more',
            'conditionals.xPurchases as purchases_x_times',
            'conditionals.start_date',
            'conditionals.end_date',
            'conditionals.plaid_category_id')
            // ->whereNull('campaigns.trigger_id', 'campaigns.offer_id', 'campaigns.conditional_id')
            ->where('campaigns.business_id', '=', $business);
    if ($query->count() === 0){
      $query = campaigns::select('*')->where('business_id', '=', $business);
    }
    return $query->get();
  }

1 个答案:

答案 0 :(得分:2)

如果未找到结果,查询生成器的get()方法将不会返回null,它将返回一个空集合。

改为检查一个空集合:

StartCoroutine(SomeMethod(...));

IEnumerator SomeMethod(...) {
    yield return Name(...par...)
    yield return Name(...par...)
    yield return Name(...par...)
    yield return Name(...par...)
}

我也建议重命名$ query的可读性,因为它没有分配查询,而是分配了结果。