如何在Laravel查询中将LIKE运算符与AND运算符配合使用

时间:2019-10-30 00:07:46

标签: php laravel eloquent laravel-6

我是有关Laravel的新手。 在视图中,我有一个带有下拉菜单的表单,其中有很多参与者。 提交表单后,参与者的值(例如“ 7”)进入控制器,控制器中存在一个查询,该查询应从数据库中检索“ id_participants”列中所有具有“ 7”的行。 不幸的是,列“ id_participants”具有格式为“ 3; 8; 65; 4; 34”的字符串。

我尝试了多种方法来解决此问题,但我只能检索记录等于“ 7”的行。

public function fetch_table(Request $request)
{
    $this->validate($request, [
        'participants' => 'required',
        'start_date' => 'required|date',
        'end_date' => 'required|date',
        'rooms' => 'required',
    ]);

    $start_date = $request['start_date'];
    $end_date = $request['end_date'];
    $participants = $request['participants'];
    $room = $request['rooms'];

    $rooms = Room::all();
    $users = User::all()->where('is_active', '1')->sortBy('surname'); 
    $meetings = Meeting::all()
    ->where('is_active', '1')
    ->where('id_room', $room)
    ->where('date', '<', $end_date)
    ->where('date', '>', $start_date)
    ->where('id_participants', $participants); //look at here

    return view('reportArea', compact('users','rooms','meetings'));
}

所以最后我应该能够执行类似的查询: SELECT * FROM meetings WHERE id_participants like "%;7" or id_participants like "7;%" or id_participants like "%;7;%" or id_participants = 7。 显然7只是一个示例...查询应该是动态的。 有人可以帮助我吗?

更新:

在尝试用以下命令替换“会议”查询后,我解决了该问题:

$meetings = DB::table('meetings')
            ->where('is_active', '1')
            ->where('id_room', $room)
            ->where('date', '>', $start_date)
            ->where('date', '<', $end_date)
            ->where(function ($query) use($participants) {
              $query->where('id_participants', $participants)
                    ->orWhere('id_participants', 'like', '%;'.$participants)
                    ->orWhere('id_participants', 'like', $participants.';%')
                    ->orWhere('id_participants', 'like', '%;'.$participants.';%');
            })
            ->get();

1 个答案:

答案 0 :(得分:1)

您可以nest your queries :(相关answer

$meetings = Meeting::all()
    ->where('is_active', '1')
    ->where('id_room', $room)
    ->where('date', '<', $end_date)
    ->where('date', '>', $start_date)
    ->where(function($query){
        $query->where('id_participants', $participants);
        $query->orWhere('id_participants', 'like', '%;'.$participants);
        $query->orWhere('id_participants', 'like', $participants.';%');
        $query->orWhere('id_participants', 'like', '%;'.$participants.';%');
    });

但是-正如评论所指出的那样,存储这样的关系效率很低。我建议您为参与者创建一个单独的多对多表。 (似乎就是它们之间的联系方式)

https://laravel.com/docs/6.x/eloquent-relationships#many-to-many