上一篇其实介绍了custombuilder,但是页面例子不够贴切。这次,使用自定义构建器来实现MySQL的find_in_set()查询。find_in_set()熟悉find_in_set的同学直接跳到下一节。find_in_set(str,list)str要查找的值list要查找的列表,字符之间用英文逗号分隔eg:foo,bar,qux返回str在列表中的位置(从1开始),如果没有找到,返回0示例:selectfind_in_set('foo','foo,bar,qux');//返回1selectfind_in_set('qux','foo,bar,qux');//返回3selectfind_in_set('abc','foo,bar,qux');//find_in_set()配合where时返回0,达到“标签”查找的目的。假如文章列表如下:idtitletag1这是一篇文章标题foo,bar,qux2这是另一篇文章标题abc,def,foo使用where+find_in_set查询标签为foo的文章。select*fromarticlewherefind_in_set('foo',`tag`);custombuilder实现find_in_set查询模型层父类继承EloquentModel,在构造方法中使用宏注册custombuilder。示例代码如下:classModelextends\Illuminate\Database\Eloquent\Model{publicfunction__construct(array$attributes=[]){/***custombuilder*//***findInSet()方法*参数:$field字段;$valuestring要查询的值*用法:查询链调用*/\Illuminate\Database\Query\Builder::macro('findInSet',function($field,$value){return$this->whereRaw("FIND_IN_SET(?,{$field})",$value);});父母::__构造($属性);}}如何使用Article::query()->findInSet('tag','foo');完成的!
