【发布时间】:2019-10-30 00:07:46
【问题描述】:
我是 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();
【问题讨论】:
-
您可以选择更改
id_participants数据格式吗? -
@elias 否,因为在会议中可以参加许多参与者,而不仅仅是一个。我无法想象另一种数据格式。
-
创建第二个表用于存储参与者。正确使用 laravel 关系,你会避免大量的代码。
-
您确实应该使用多对多关系。一般来说,除非完全必要,否则避免将数组、对象等添加到数据库中,因为您现在面临的问题是我们将其分开的原因。查看数据库规范化、laravel 外键迁移和关系。
标签: php laravel eloquent laravel-6