如何在laravel中跳过具有文件的行存在条件

时间:2015-06-13 17:44:39

标签: laravel search eloquent

这是针对基于许多输入字段的搜索查询,我正在根据输入执行查询中的if语句,例如:

$query = Model::all();

if($field = Input::get('field'))
        $query->where('column_name', $field);

但是如果没有具有该行ID名称的图像,我想要做的是跳过一行的条件,如下所示:

if( file_exists('/img/'.$this_query->id) )
        $query->skip();

1 个答案:

答案 0 :(得分:1)

选项1:创建文件名数组,然后使用whereIn查询构建器方法,该方法检查数组中列值的出现。

$query = Model::query();

$filenames = scandir('/img');

// the following excludes any id's not in the $filenames array
$query = $query->whereIn('id', $filenames);

选项2:运行查询,然后在Laravel中生成filter生成的集合。

$query = Model::query();
// ... then build up your query

// the following gets the query results and then filters them out
$collection = $query->get()->filter( function($item) {
    return file_exists('/img/'.$item->id);
}

原理:数据库在处理过程中无法检查文件系统;所以你需要(选项1)提供一个列表来检查,或者(选项2)在之后检查get()从查询返回结果。