上篇文章其实曾经介绍了自定义 builder,可是举得了 page 例子不够失当,这次用自定义 builder 实现一下 MySQL 的 find_in_set() 查问。

find_in_set()

相熟 find_in_set 的同学间接跳至下一节。

find_in_set(str, list)

str 要搜寻的值
list 待搜寻列表,字符间以英文逗号分隔 eg: foo,bar,qux
返回 str 在 list 中的地位(从1开始),搜寻不到则返回0

例子:

select find_in_set('foo', 'foo,bar,qux'); // 返回1select find_in_set('qux', 'foo,bar,qux'); // 返回3select find_in_set('abc', 'foo,bar,qux'); // 返回0

当 find_in_set() 与 where 配合能达到“标签”搜寻的目标。如果文章表如下:

idtitletag
1This is an article titlefoo,bar,qux
2This is another article titleabc,def,foo

应用 where + find_in_set 能够查问带 foo 标签的文章。

select * from article where find_in_set('foo', `tag`);

自定义 builder 实现 find_in_set 查问

模型层父类继承 Eloquent Model ,在构造方法中利用 macro 注册自定义的 builder。示例代码如下:

class Model extends \Illuminate\Database\Eloquent\Model{    public function __construct(array $attributes = [])    {        /**         * 自定义 builder         */        /**         * findInSet() 办法         * 参数: $field 字段 ;$value string 要查问的值         * 应用办法:query链式调用         */        \Illuminate\Database\Query\Builder::macro('findInSet', function ($field, $value) {            return $this->whereRaw("FIND_IN_SET(?, {$field})", $value);        });        parent::__construct($attributes);    }}

如何应用

Article::query()->findInSet('tag', 'foo');

Finished!