推荐几个你们可能没用过的查询构造器的方法
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 协议》,转载必须注明作者和本文链接
firstWhere 我在Laravel 6 中没有搜到
明明有弄了这么好用的查询方法,为什么不把它写 明在文档里内呢