【问题标题】:Laravel check if a string contains a word from a databaseLaravel 检查字符串是否包含数据库中的单词
【发布时间】:2020-03-29 01:22:33
【问题描述】:

我有一个包含员工列表的表,我有一个可以包含员工姓名的字符串。

我创建了一个 SQL 查询来显示字符串中已经存在的员工的姓名。但我无法将其翻译成查询 Laravel。

如何在 Laravel 中编写这个请求?

SELECT title from employes WHERE "my string" like concat("%", title, "%")

【问题讨论】:

  • 这个字符串是什么样子的,用逗号或其他东西分隔?最好的办法是分解该字符串并使用循环来检查确切的用户名,而不是使用like
  • 引用 OP:"string of character : "the employee Antoine is on leave, he must be replaced by Lionel.... Employees table: Antoine, Lionel ...... how can you recover these names !?"

标签: mysql laravel eloquent query-builder


【解决方案1】:

你的支票是倒置的,这使得写起来不必要地复杂,你应该改用WHERE title LIKE '%my string%'

然后在 Laravel 中:

Employee::where('title', 'like', '%' . $myString . '%')->get();

【讨论】:

  • 我认为OP意味着字符串"my string"会有很多名字...
  • 抱歉,这个查询没有给出任何信息!示例:字符串:“员工 Antoine 正在休假,他必须由 Lionel 代替......员工表:Antoine,Lionel ......你怎么能恢复这些名字!?
【解决方案2】:

您可以使用 DB 外观并在控制器中执行 SQL 查询,如下所示:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class EmployeeController extends Controller
{
    /**
     * Show a list of all of the employes.
     *
     * @return Response
     */
    public function index()
    {

        $myString = 'test';
        $employees = DB::select('SELECT title from employees WHERE title like "%'.$myString.'%"', [$myString]);

        return view('user.index', ['users' => $users]);
    }
}

【讨论】:

    【解决方案3】:

    试试下面的代码:

    在 laravel 中,你应该使用以下查询

    $string = "the employee Antoine is on leave, he must be replaced by Lionel";
    
    $findstring = explode(' ', $string); 
    
    $emp = Employee::where(function ($q) use ($findstring) {
           foreach ($findstring as $value) {
                $q->orWhere('title', 'like', "%{$value}%");
           }
           })->select('title')->get();
    
    dd($emp);
    

    【讨论】:

    • 两者都没有给出好的结果,这个查询 SQL SELECT title from employees WHERE "my string" like concat("%", title, "%") 很简单。给了我一个很好的结果,我正在寻找如何在 laravel 中转换?
    • @visulo 是的,你是对的。在 SQL 查询中工作。但是当在 laravel 查询构建器中使用上面的例子时。
    【解决方案4】:
    $message = $request->input('message');
    if($message) {
        $findstring = explode(' ', $message); 
        $excluded = DB::table('word_list')->where(function ($q) use ($findstring) {
            foreach ($findstring as $value) {
                $q->orWhere('words', 'like', "%{$value}");
            }
        })->select('words')->first();
    }
    if($excluded != null) {
        return response()->json(['success'=>false,'excluded'=>$excluded,'message'=>' This is an excluded message','status'=>'message not send']);
    } else {
        broadcast(new NewMessage($message));
        return response()->json(['success'=>true,'message'=>$message,'status'=>'message sent']);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2012-11-27
      相关资源
      最近更新 更多