Laravel模型只在一半的时间内返回结果


Laravel model is only returning results half of the time

我有一个名为show()的方法,它将从数据库中获取目的地,但它首先在提供的输入中检查location键。

public function show()
{
  // Fetch the appropriate destinations
  if (Input::has('location')) {
    $destinations = Destination::where('type', '=', Input::get('type'))
      ->where('city', '=', Input::get('location'))
      ->with('city', 'state', 'type')
      ->get();
  } else {
    $destinations = Destination::where('type', '=', Input::get('type'))
      ->with('city', 'state', 'type')
      ->get();
  }
  'Log::debug($destinations);
  return $destinations;

这非常好,但只有一半的时间。有时它返回一个空数组([]),有时它按预期返回所有结果。

起初我以为这是我的JavaScript,但事实证明,从PHP直接将其记录到控制台在大多数时候也会返回一个空数组,但并非总是如此。

是什么可能导致这样的事情发生?

首先确保始终传递完全相同的数据(同时记录输入数据)。例如,一次你通过了"汉诺威"和第二次通过了"Hanover"——看起来几乎一样,但会完全改变结果。因此,您可能应该添加修剪数据(如果您还没有这样做的话)。

另一个潜在问题是:

$destinations = Destination::where('type', '=', Input::get('type'))
      ->where('city', '=', Input::get('location'))
      ->with('city', 'state', 'type')
      ->get();

destinations表中有city列吗?如果是,您是否也与名称city有关系?对我来说,这似乎是一个错误。此外,您永远不应该在数据库中的表中创建和列同名的关系,否则迟早会遇到麻烦。