推荐几个你们可能没用过的查询构造器的方法

1. Model()->getQuery()->whereNotKey($id);
2. Model()->getQuery()->whereKey($id);
3. Model()->firstWhere();

首先看第一个把

/**
     * Add a where clause on the primary key to the query.
     *
     * @param  mixed  $id
     * @return $this
     */
    public function whereKeyNot($id)
    {
        if (is_array($id) || $id instanceof Arrayable) {
            $this->query->whereNotIn($this->model->getQualifiedKeyName(), $id);

            return $this;
        }

        return $this->where($this->model->getQualifiedKeyName(), '!=', $id);
    }

我们有时候需要查询 id != xxx 或者 id not in (1,2,3)。
我们在构建器中需要 where (‘id’,’<>’,1); 或者 whereNotIn (‘id’,[1,2,3])。
这时候 whereKeyNot ($mixed) 就能更方便的派上用场了。
源码中做了自适应,如果传递 id 是数组或者集合类型就当 whereNotIn 处理,如果不是,就当!= 处理非常好用。

2.whereKey()

/**
     * Add a where clause on the primary key to the query.
     *
     * @param  mixed  $id
     * @return $this
     */
    public function whereKey($id)
    {
        if (is_array($id) || $id instanceof Arrayable) {
            $this->query->whereIn($this->model->getQualifiedKeyName(), $id);

            return $this;
        }

        return $this->where($this->model->getQualifiedKeyName(), '=', $id);
    }

Key 与 KeyNot 与之相反 就不说了。

3.firstWhere()

/**
     * Add a basic where clause to the query, and return the first result.
     *
     * @param  \Closure|string|array  $column
     * @param  mixed  $operator
     * @param  mixed  $value
     * @param  string  $boolean
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    public function firstWhere($column, $operator = null, $value = null, $boolean = 'and')
    {
        return $this->where($column, $operator, $value, $boolean)->first();
    }

这里可以看到就是普通的 where () 只不过帮你执行了 first (),相当于你可以少写一个 ->first ()
这里用来 where 语句收尾还是挺方便的 Model::whereName (‘xxx’)->firstWhere (‘status’,1)

本作品采用《CC 协议》,转载必须注明作者和本文链接
Mr.pan
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

firstWhere 我在 Laravel 6 中没有搜到

4年前 评论
pan_zoe (楼主) 4年前

明明有弄了这么好用的查询方法,为什么不把它写 明在文档里内呢

4年前 评论
pan_zoe (楼主) 4年前