laravel查询构造器中whereNotKey,whereKey,firstWhere用法详解
Laravel  /  管理员 发布于 2020-07-06 10:44:45   1009
laravel查询构造器中whereNotKey,whereKey,firstWhere用法详解
1.whereNotKey()
我们有时候需要查询 id != xxx 或者 id not in (1,2,3)。
我们在构建器中需要 where (‘id’,’<>’,1); 或者 whereNotIn (‘id’,[1,2,3])。
这时候 whereKeyNot ($mixed) 就能更方便的派上用场了。
源码中做了自适应,如果传递 id 是数组或者集合类型就当 whereNotIn 处理,如果不是,就当!= 处理非常好用。
/**
* 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);
}
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);
}
3.firstWhere()
这里可以看到就是普通的 where () 只不过帮你执行了 first (),相当于你可以少写一个 ->first ()
这里用来 where 语句收尾还是挺方便的 Model::whereName (‘xxx’)->firstWhere (‘status’,1)
/**
* 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();
}
想了解更多查询构造器知识,请自行搜索
博主 在
nginx中500,501,502,503,504,505状态码的详解及出现的原因/区别中评论 有错误可以指正吧 没必要搞人心态 老铁 信不信我删库跑路..博主 在
国内用什么翻墙使用谷歌?上外网神器Ghelper插件详解中评论 @白马 最近是很不稳定,后面我会找找其它更稳定的方式,发表一篇博文..白马 在
国内用什么翻墙使用谷歌?上外网神器Ghelper插件详解中评论 显示:暂停注册。。这注册不了啊,该怎么办呢?..博主 在
国内用什么翻墙使用谷歌?上外网神器Ghelper插件详解中评论 @请教 小图标没有出现 重复检查步骤5,进去看看右下角是否开启..请教 在
国内用什么翻墙使用谷歌?上外网神器Ghelper插件详解中评论 你好,我也遇到了安装完右上角没有显示图标,也不能打开相关网页的问题,用的是谷歌浏..Auther ·HouTiZong© 2009-2020 zongscan.com 版权所有ICP证:
粤ICP备20027696号
也可以扫右边的二维码