自用 ORM,原生 PHP,模拟 Laravel 的调用方式
拼接 sql 条件
- where
-
where('name', 'John')
-
where('status', '<>', 1)
-
where([['status', '=', 1], ['subscribed', '<>', '1']])
-
where(function ($query) {
$query->where('votes', '>', 200)
->orWhere('title', '=', 'Admin'); })
-
- join
- join('contacts', 'users.id', '=', 'contacts.user_id')
- leftjoin
- leftjoin('posts', 'users.id', '=', 'posts.user_id')
- rightjoin
- rightjoin('posts', 'users.id', '=', 'posts.user_id')
- whereNull
- whereNull('first_name')
- orWhere
- orWhere('name', 'John')
- orWhere('title', '=', 'Admin')
- whereIn
- whereIn('id', [1, 2, 3])
- whereNotIn
- whereNotIn('id', [1, 2, 3])
- whereNotNull
- whereNotNull('updated_at')
执行 sql 语句
- find
- find(1)
- find([1, 2, 3])
- first
- get
- count
- insert
- update
- update(['active' => true])
- increment
- increment('votes')
- increment('votes', 5)
- decrement
- decrement('votes')
- decrement('votes', 5)
- delete
- softDeletes
- 使用 is_deleted 删除
- exists
聚合、排序
- orderBy
- orderBy('id')
- orderBy('name', 'desc')
- latest
- 使用 created_at 排序
- oldest
- 使用 created_at 排序
- groupBy
- groupBy('account_id')
- groupBy('first_name', 'status')
- offset
- offset(10)
- limit
- limit(5)
引入
require('/path/to/Database/DatabaseLoad.php');
Database\DatabaseLoad::register_autoloader();
定义一个模型
use Database\Eloquent\Model;
class Animal extends Model
{
public $table = 'table_name'; // 指定模型对应的表
// 定义一个关联关系
public function Bird()
{
return $this->hasOne(Bird::class, 'foreign_id'); // 指定关联模型的类名,外键名
}
}
使用
$animal = new Animal();
$bird = $animal->Bird();
$birds = $bird
->where(function ($query) {
$query->where('can_fly', 1)
->whereIn('id', [6, 7]);
})
->where('is_del', 0)
->get();