【问题标题】:How to check a string is matching with 2 columns in database - Laravel如何检查字符串是否与数据库中的 2 列匹配 - Laravel
【发布时间】:2021-07-16 18:10:36
【问题描述】:

我正在处理一个场景,我想从 URL 中搜索字符串值匹配数据库中的 2 列。例如..在我的项目系统中,在输入 web URL(如 website.com/nayanachandran)时,有客户 first_name 和 last_name

必须从客户数据库中检查单词“nayanachandran”,使用 laravel 查询,例如客户 first_name 和 last_name 的组合等于请求参数中的字符串。 目前,我这样做的方式就像在字符串中添加了 hi-pen 例如:nayana-chandran

在搜索时,我在存储库中添加了查询,例如:

    $publicUrl = explode("-",$this->request->unique_name);
    $coach_details = Customer::where('first_name', $publicUrl['0'])->where('last_name', $publicUrl['1'])->first();

有什么帮助吗?

【问题讨论】:

    标签: mysql laravel


    【解决方案1】:

    好的,所以一种方法是:

    $publicUrl = explode('-', $this->request->unique_name);
    list($firstName, $lastName) = $publicUrl;
    

    这确实从以'-'分隔的字符串创建了一个数组,然后简单地做一个:

    Customer::where([['first_name', $firstName],['last_name', $lastName]])->first();
    

    这将返回与该条件相关的客户对象。

    但是,我建议您改用查询字符串,并且只需使用如下地址:

    https://address.com/example?first_name=james&last_name=smith
    

    这将使爆炸变得不必要,因为您可以直接从请求对象访问这些值:

    Customer::where([['first_name', request()->get('first_name')],['last_name', request()->get('last_name')]])->first();
    

    【讨论】:

      【解决方案2】:

      听起来您在问如何从 url 中获取串联的字符串 nayanachandran,然后在您的数据库中将其作为 first_namelast_name 列的组合进行搜索。

      假设是这种情况,您可以使用whereRawCONCAT 的组合:

      Customer::whereRaw("CONCAT(first_name, last_name) = ?", [$this->request->unique_name])->first();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-08
        • 1970-01-01
        • 1970-01-01
        • 2010-12-19
        • 1970-01-01
        • 2013-03-12
        • 2020-05-16
        相关资源
        最近更新 更多