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

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

问题描述:

So, basically I have a field in a table from my database which contains some values separated by comma (something like: 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.

所以,基本上我在数据库的表中有一个字段,其中包含一些用逗号分隔的值(类似于: value1,value2,value3 code>)。 我需要以某种方式检查这些值中的一个或多个是否包含在值数组中并检索模型。 我想要一个使用Eloquent Model Query来实现这一目标的解决方案,如果模型查询不可能,那么查询生成器解决方案也可以,或者可能是替代方案。 p> div>

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:

$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.