使用selectraw和like对sql、laravel分数/排名结果进行排序?

c86crjj0  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(413)

这只适用于一个名字。。。

Result::whereIn('id', $log->result_ids)
      ->select('*')
      ->selectRaw("(owner LIKE ? ) + 
                   (owner LIKE ? ) + 
                   (city LIKE ? ) AS score", 
                   ['%CHARLOTTE%', '%RICHARD%', 'Salem'])
      ->get();

但我想动态地使用一组所有者、城市等。。。

$owners = [ 
     'CHARLOTTE', 
     'RICHARD'
     // ... or more 
];
$cities = [ 
     'SALEM', 
     'PORTLAND'
     // ... or more 
];

Result::whereIn('id', $log->result_ids)
      ->select('*')
      ->selectRaw("(owner LIKE ? ) + 
                   (city LIKE ? ) AS score", 
                   [$owners, $cities])
      ->get();

@迈赫迈特büt型ün、 这是我对你答案的修改版本,它确实有效。有没有更干净的方法?

$spouses = ['Patricia', 'Cindy'];
$cities  = ['Riverside', 'San Diego'];

$string_to_spouse_score = collect($spouses)->map( function($spouse) {
      return "(owner LIKE '%".strtoupper($spouse)."%' )";
})->join(' + ') . " as spouse_score";

$cities_string = collect($cities)->map( function($city) {
      return strtoupper($city);
})->join(' OR city LIKE ');

Result::whereIn('id', $result_ids)->select('*')
      ->selectRaw("(owner LIKE ? ) as owner_score", ['%'.strtoupper($owner->first_name).'%'])
      ->selectRaw($string_to_spouse_score) // as spouse_score
      ->selectRaw("(city LIKE ? ) as city_score", [$cities_string])
      ->selectRaw("(SELECT(owner_score)) + (SELECT(spouse_score)) + (SELECT(city_score)) as score")
      ->having('score', '>', 0)
      ->orderBy('score', 'desc')
      ->get();
0tdrvxhp

0tdrvxhp1#

你想用 array 而不是 string . 试试这个(我希望它能起作用):

$owners = [ 
     'CHARLOTTE', 
     'RICHARD'
     // ... or more 
];
$cities = [ 
     'SALEM', 
     'PORTLAND'
     // ... or more 
];

$new_owners=array();
foreach ($owners as $owner){
    $new_owners[]='%'.$owner.'%';
}
$owners_query_string= implode(' OR owner LIKE ', $new_owners);

$new_cities=array();
foreach ($cities as $city){
    $new_cities[]='%'.$city.'%';
}
$cities_query_string= implode(' OR city LIKE ', $new_cities);

Result::whereIn('id', $log->result_ids)
      ->select('*')
      ->selectRaw("(owner LIKE ? ) + 
                   (city LIKE ? ) AS score", 
                   [$owners_query_string, $cities_query_string])
      ->get();

相关问题