【问题标题】:Laravel How to join table and merge columns, then set a 'LIKE' query on Eloquent?Laravel 如何连接表和合并列,然后在 Eloquent 上设置“LIKE”查询?
【发布时间】:2019-07-31 07:02:18
【问题描述】:

环境:

Laravel 5.7.28

数据库mysql

CentOS 7.2

我有 3 个如下表,我需要加入这 3 个表并合并列 (customer.first_name,customer.last_name,customer.address,job.name,job.address,job.date) 设置“喜欢”查询。

例如, 库尔姆斯合并后customer.first_name,customer.last_name,customer.address,job.name,job.address,job.date customer.first_name + customer.last_name + customer.address + job.name + job.address +job.date 是 'TOMSMITHCecilia ChapmanABC.LtdIris Watson2019-01-10',所以

 when $text = 'MS';
set  'like' '%'.$text.'%' will return below result


customer.first_name = TOM

customer.last_name = SMITH

customer.address = Cecilia Chapman

job.name = ABC.Ltd

job.address = Iris Watson

job.date = 2019-01-10

  1. id 表(关系属于表客户和工作)
    • 身份证
    • customer_id
    • job_id
  2. 客户表
    • 身份证
    • 名字
    • 姓氏
    • 地址
  3. 工作编号
    • 身份证
    • 姓名
    • 地址
    • job_date

【问题讨论】:

  • 你先尝试了吗?如果是,请显示代码。

标签: php laravel laravel-5


【解决方案1】:

看到这个

\DB::table('id')->join('customer','customer.customer_id','id.customer_id')
->join('job','job.id','id.job_id')
->where('customer.first_name', 'LIKE', '%' . $text . '%')
->orWhere('customer.last_name', 'LIKE', '%' . $text . '%')
->orWhere('customer.address', 'LIKE', '%' . $text . '%')
->orWhere('job.name', 'LIKE', '%' . $text . '%')
->orWhere('job.address', 'LIKE', '%' . $text . '%')
->get();

【讨论】:

  • 我需要加入这 3 个表并合并列 (customer.first_name,customer.last_name,customer.address,job.name,job.address,job.date) 以设置“喜欢”查询。没有设置或在哪里。我的例子是 first_name + last_name = TOMSMITH 所以当 $text = 'MS'; set 'like' '%'.$text.'%' 可以返回打击(合并 customer.first_name 和 customer.last_name),因此示例结果
【解决方案2】:

如果您有多个 where 条件,那么您可以将 where 函数与 orWhere 一起使用,如下所示:

\DB::table('id')->join('customer','customer.customer_id','id.customer_id')
->join('job','job.id','id.job_id')
->where(function ($query) use($text) {
                $query->where('customer.first_name', 'LIKE', '%' . $text .'%')
                      ->orWhere('customer.last_name', 'LIKE', '%' . $text . '%')
                      ->orWhere('customer.address', 'LIKE', '%' . $text . '%')
                      ->orWhere('job.name', 'LIKE', '%' . $text . '%')
                      ->orWhere('job.address', 'LIKE', '%' . $text . '%')
            })->get();

【讨论】:

  • 我需要加入这 3 个表并合并列 (customer.first_name,customer.last_name,customer.address,job.name,job.address,job.date) 以设置“喜欢”查询。没有设置或者我的例子是 first_name + last_name = TOMSMITH 所以当 $text = 'MS'; set 'like' '%'.$text.'%' 可以返回打击(合并 customer.first_name 和 customer.last_name),因此示例结果
猜你喜欢
  • 2019-02-13
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
相关资源
最近更新 更多