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

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
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

firstWhere 我在Laravel 6 中没有搜到

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

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

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

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!