eloquent_dart 0.1.1 copy "eloquent_dart: ^0.1.1" to clipboard
eloquent_dart: ^0.1.1 copied to clipboard

Eloquent ORM extracted from Vania framework for Dart and Flutter.

Eloquent Dart #

Eloquent ORM extracted from the Vania framework, adapted for standalone use in Flutter and Dart applications with SQLite support.

Features #

  • Eloquent ORM: A beautiful and simple ActiveRecord implementation for working with your database.
  • SQLite Support: Built-in support for SQLite using the sqlite3 package.
  • Query Builder: Fluent interface for building SQL queries.
  • Relationships: Support for One-to-One, One-to-Many, Many-to-Many and Polymorphic relationships.

Installation #

Add eloquent_dart to your pubspec.yaml:

dependencies:
  eloquent_dart: ^0.1.0

Usage #

1. Setup Connection #

Initialize the database connection before using any models. This is typically done in your main() function.

import 'package:eloquent_dart/eloquent_dart.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

Future<void> main() async {
  // Get a location to store the database file
  Directory documentsDirectory = await getApplicationDocumentsDirectory();
  String path = join(documentsDirectory.path, "app.db");

  // Configure the database
  DBConfig config = DBConfig(
    driver: 'sqlite',
    filePath: path, // Uses in-memory if omitted and openInMemorySQLite is true
  );

  // Connect
  await ConnectionManager().connect(config, 'default');
  
  runApp(MyApp());
}

2. Define Models #

Create a class that extends Model.

import 'package:eloquent_dart/eloquent_dart.dart';

class User extends Model {
  @override
  String get tableName => 'users';
  
  // Optional: Define fillable fields for mass assignment
  @override
  List<String> get fillable => ['name', 'email'];
}

3. Querying #

// Retrieve all users
final users = await User().query.get();

// Find a user by ID
final user = await User().query.find(1);

// Filter users
final activeUsers = await User().query.where('status', '=', 'active').get();

// Complex queries
final users = await User().query
    .where('votes', '>', 100)
    .orWhere('name', '=', 'John')
    .orderBy('name', 'desc')
    .limit(10)
    .get();

4. Inserts, Updates, and Deletes #

Insert

await User().query.insert({
  'name': 'Jane Doe',
  'email': 'jane@example.com'
});

Update

await User().query.where('id', '=', 1).update({
  'email': 'new_email@example.com'
});

Delete

await User().query.where('id', '=', 1).delete();

Migrations #

Create a Migration #

You can create a migration by extending the Migration class.

import 'package:eloquent_dart/eloquent_dart.dart';

class CreateUsersTable extends Migration {
  @override
  Future<void> up() async {
    await super.create('users', (Schema t) {
      t.id();
      t.string('name');
      t.string('email').unique();
      t.timeStamp('created_at').nullable();
      t.timeStamp('updated_at').nullable();
      t.softDeletes();
    });
  }

  @override
  Future<void> down() async {
    await super.drop('users');
  }
}

Running Migrations #

To run migrations, you need to set up the MigrationConnection and execute the up method.

import 'package:eloquent_dart/eloquent_dart.dart';

void main() async {
  Map<String, dynamic> migrationConfig = {
    'default': 'sqlite',
    'connections': {
      'sqlite': {
        'driver': 'sqlite',
        'database': 'database.sqlite',
      }
    }
  };
  
  await MigrationConnection().setup(migrationConfig);

  await CreateUsersTable().up();
}

Relationships #

Eloquent Dart supports standard relationships.

One To Many

class User extends Model {
  // ...
  
  // Define relationship
  void posts() {
    hasMany('posts', Post());
  }
}

// Usage
// Ensure you call include() to load the relationship
final usersWithPosts = await User().query.include('posts').get();

migrations #

Currently, this package does not include the Vania migration runner. You can execute raw SQL to create tables using the connection manager:

await ConnectionManager().connection('default')?.execute('''
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  );
''');

License #

MIT

0
likes
120
points
30
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Eloquent ORM extracted from Vania framework for Dart and Flutter.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

collection, meta, path, sqlite3

More

Packages that depend on eloquent_dart