如何使用子查询编写以下查询?

How to write the below query using subquery?

我正在尝试从国家 table 获取货币,如果行存在 else return null,如下面的代码所示。

$country = Country::where("id", 619);
if($country->exists()){
    $currency = $country->first()->currency;
} else {
    $currency = "USD;";
}

你可以使用这个快捷方式

$currency = Country::where("id", 619)->first()->currency ?? 'USD';

如果国家/地区存在,这将 return 货币,如果不存在,它将 return 美元

您必须先在模型中添加一个关系。你可以找到这个 in the documentation of Laravel. After this you have multiple ways to do this, for only a check the best way is the ::has($relation) function that you can find here.

您的另一个选择是使用函数 ::with($relation) 加入 table。完成此操作后,您可以像往常一样使用 ::where($column, $value) 函数检查连接的 table 的列。我认为这回答了您关于如何进行子查询的问题。

模型中关系函数的例子class.

function currency() {
  return $this->hasOne(Country:class, 'code', 'country');
}

子查询示例

$hasCurrency = Country::has('currency');
$currency = null;

if ($hasCurrency) {
  $result = Country::with('currency')
    ->where('id', 619)
    ->where('currency.active', 1)
    ->first();

  $currency = $result->currency->code;
}

一个易于编写的解决方案是

$currency = Country::where("id", 619)->value('currency') ?? 'USD;';

这不会加载 Country 的实例(不使用 first())并将 return“货币”属性的值或 null 如果没有可用结果。