【问题标题】:use of orWhere() in Eloquent在 Eloquent 中使用 orWhere()
【发布时间】:2020-10-03 18:57:03
【问题描述】:

我有一个雄辩的查询,我运行了两次,但感觉可以运行一次。

如果存在,我想返回第一个 where 语句的值,否则检查第二个 where 语句,它是查询中的默认值。

这就是我目前正在做的事情:

$details = Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
         ->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
         ->where('telco_prefixs.prefix', '=',  $phone_number) // check if ndc exists
         ->first();


if ($details){

    return $details;
}

    return Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
         ->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
         ->where('telcos.name', '=', 'Default') //default channel
         ->first();

我觉得这可以组合成如下内容:

但是,这会因为继续执行 OrWhere 子句而失败。

Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
     ->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
     ->where('telco_prefixs.prefix', '=', $phone_number)    // if ndc exists
     ->Orwhere('telcos.name', '=', 'Default')    //default channel
     ->first();

有人帮忙。谢谢

【问题讨论】:

标签: laravel eloquent


【解决方案1】:

尝试添加您的 where 和 or where 条件,如下所示。

Telco::select('telcos.id AS telco_id', 'telcos.name AS telco_name')
     ->leftJoin('telco_prefixs', 'telco_prefixs.telco_id', '=', 'telcos.id')
     ->where(function ($query) use($phone_number) {
          $query->where('telco_prefixs.prefix', '=', $phone_number);
          $query->Orwhere('telcos.name', '=', 'Default');
     })->first();

【讨论】:

    【解决方案2】:

    我只想用雄辩的方式,一个可能的解决方案是:

    我想你有一个叫做 Telco 的模型和另一个叫做 TelcoPrefix 的模型。

    //Telco.php
    //first we create a has many relationship with your telco_prefixs table.
    public function telcoPrefixs(){
        return $this->hasMany(TelcoPrefix::class);
    }
    

    一旦你有了这种关系,你就可以使用类似于这段代码的东西:

    Telco::whereHas('telcoPrefixs',function($query, $phone_number){
      return $query->where('prefix,'=',$phone_number);
    })->select('id','name')->first();
    

    这将比较关系,如果它存在或有,它将在一个查询中返回您的第一条记录。

    希望它至少可以帮助您指导您可以做什么。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2021-07-12
      • 2018-01-30
      • 2019-05-24
      相关资源
      最近更新 更多