【问题标题】:search in a table and its relations in laravel在 laravel 中搜索表及其关系
【发布时间】:2021-12-15 01:50:19
【问题描述】:

我需要在预约表中搜索代码或作为预约关系的患者姓名。这是我到目前为止达到的代码,但它不起作用:

$lab = Lab::select('id', 'code')
->Where('code', 'like', "%{$search_query}%")
->with(['patient' => function ($q) {
    $q->select('id', 'avatar', DB::raw('CONCAT(first_Name, " ", second_Name) AS name')
    ->where('name', 'like', "%{$search_query}%")
    ->orWhereRaw("concat(first_name, ' ', second_name) like '%$search_query%' ")
);}])
->limit(5)
->get();      

【问题讨论】:

  • 尝试将您的代码 "%{$search_query}%" 更改为 '%'.$search_query.'%"
  • 我已经试过了,可惜没用

标签: php mysql sql laravel eloquent


【解决方案1】:

use ($search_query) 添加到您的::with() 部分:

$lab = Lab::with(['patient' => function ($q) use ($search_query) {
        $q->select('id', 'avatar', DB::raw('CONCAT(first_Name, " ", second_Name) AS name')
            ->where('name', 'like', "%{$search_query}%")
            ->orWhereRaw("concat(first_name, ' ', second_name) like '%$search_query%' ")
        );
    }])
        ->select('id', 'code')
        ->Where('code', 'like', "%{$search_query}%")
        ->limit(5)
        ->get();

【讨论】:

  • 它给了我一个错误 in (->where('name', 'like', "%{$search_query}%")) where is undefined
【解决方案2】:

您可以使用whereHas 对 Laravel 关系进行如下条件:

$lab = Lab::select('id', 'code')
        ->Where('code', 'like', "%{$search_query}%")
        ->whereHas('patient', function ($q) use ($search_query){
            $q->where('patients.name', 'like', "%{$search_query}%");
        }) 
        ->limit(5)
        ->get(); 

【讨论】:

  • 它没有显示结果:(
  • 使用->toSql()代替->get()转储查询并在您的数据库中运行它以查看查询是否有任何错误
猜你喜欢
  • 1970-01-01
  • 2021-10-22
  • 2015-10-30
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多