laravel中在model里面重写where怎么写?

我在 laravel 中使用 mongodb 作为 db 驱动,每次查找数据 都是 where ([“_id”=>1]) 使用_id ,我想兼容一下 都换成 where ([“id”=>1]) 用 id 作为查询条件,想着能不能重写 where 然后当查询 id 的时候换成查询_id , 不知道怎么用?有大佬知道的吗?

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 12

没有的,你只是兼容处理主键的话whereKey更好用

1年前 评论
test2018 (楼主) 1年前
test2018

这样写确实可以实现效果 但是不知道有没有隐患

public function where($column){
        if(isset($column['id'])) {
            $column['_id'] = $column['id'];
            unset($column['id']);
        }
        return static::query()->where($column);
}



1年前 评论
relax_tortoise 1年前
relax_tortoise 1年前
gongmeng 1年前

使用局部作用域:快速入门《Laravel 9 中文文档》 可达到这个需求

public function scopeMongodbId($query, $id, $operator = "=")
{
    return $query->where('_id', $operator, $id);
}

$users = User::mongodbId($id, ">")->get();
1年前

没有用 mongodb 的 ORM 吗

1年前

全局作用域(软删除就是这么实现的)
快速入门《Laravel 6 中文文档》

1年前

光就这一点,实数没必要

1年前
//AppServiceProvider里面注册一个宏
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
...
Builder::macro('whereMongodbId', function ($id,$op = '=',$key = '_id') {
    $this->where($key,$op,$id);
    return $this;
 });
EloquentBuilder::macro('whereMongodbId', function ($id,$op = '=',$key = '_id') {
    $this->getQuery()->where($key,$op,$id);
    return $this;
});
//使用
DB::name('some_table')->whereMongodbId(123)->first();
AModel::whereMongodbId(123)->first();

//或者激进点
Builder::macro('IdEq', function ($id) {
    $this->where('_id','=',$id);
    return $this;
});
Builder::macro('IdLt', function ($id) {
    $this->where('_id','<',$id);
    return $this;
});
Builder::macro('IdGt', function ($id) {
    $this->where('_id','>',$id);
    return $this;
});
1年前
nff93

这个 ORM 不会自动处理嘛?

1年前

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