简体   繁体   English

Laravel 5:如何验证数据中是否包含以逗号分隔的数据库表字段中的值?

[英]Laravel 5: How to verify if values separated by comma from a database table field are contained in an array?

So, basically I have a field in a table from my database which contains some values separated by comma (something like: value1, value2, value3 ). 所以,基本上我在数据库的表中有一个字段,其中包含一些用逗号分隔的值(类似于: value1, value2, value3 )。 I need to check somehow if one or more of these values are contained in an array of values and retrieve the model(s). 我需要以某种方式检查这些值中的一个或多个是否包含在值数组中并检索模型。 I'd like a solution using Eloquent Model Query to achieve this, if not possible with Model Query, then a Query Builder solution will be okay as well, or maybe something alternative. 我想要一个使用Eloquent Model Query来实现这一目标的解决方案,如果模型查询不可能,那么查询生成器解决方案也可以,或者可能是替代方案。

Tried to use a function inside the where statement where I loop the array of values and just query the model using like operator to check if field value matches the values from the array and in the end I got something like this: 试图在where语句中使用一个函数,我where其中循环值数组,并使用like运算符查询模型,以检查字段值是否与数组中的值匹配,最后得到如下内容:

$devices = explode(",", Input::get("devices"));
$products = Product::where(function ($q) use ($devices) {
   foreach ($devices as $device) {
      $q->orWhere("compatible_devices", "like", "%" . $device . "%");
   }
})->get();

Works quite well so far. 到目前为止工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM