flutterflutter-moor

Flutter: Select from two table with distinc in Moor Database


I have query SQL like this:

SELECT DISTINCT LST_KURS.LKU_ID, LST_KURS.LKU_SYMBOL FROM LST_PRODUCT_CALC join LST_KURS WHERE LST_PRODUCT_CALC.LKU_ID = LST_KURS.LKU_ID AND LST_PRODUCT_CALC.PSET_ID = #{psetId}

How to write that query on moor?

This is my table of LST_KURS:

import 'package:moor/moor.dart';

class LstKurs extends Table {
  @override
  String get tableName => 'LST_KURS';

  TextColumn get lkuId => text().named('LKU_ID')();

  IntColumn get lsneId => integer().named('LSNE_ID').nullable()();

  TextColumn get lkuSymbol => text().named('LKU_SYMBOL').nullable()();

  @override
  Set<Column> get primaryKey => {lkuId};
}

This is my table of lst_prodset_calc:

import 'package:moor_flutter/moor_flutter.dart';

class LstProdsetCalc extends Table {
  @override
  String get tableName => 'lst_prodset_calc';

  IntColumn get psetId => integer()
      .named('PSET_ID')
      .customConstraint('NULL REFERENCES lst_prodset (PSET_ID)')();

  TextColumn get lkuId => text().named('LKU_ID')();

  @override
  Set<Column> get primaryKey => {psetId, lkuId};
}

This is my function in Dao:

Future<List<String>> getListKurs(int psetId) {
    // idk how to write that query on moor in here
  }

Solution

  • First create your model first.

    class KursSymbol {
      final String lkuId;
      final String lkuSymbol;
      KursSymbol({
        this.lkuId,
        this.lkuSymbol,
      });
    }
    

    And modified your dao function.

    Future<List<KursSymbol>> getKursSymbol(int psetId) {
        return customSelect(
            'SELECT DISTINCT LST_KURS.LKU_ID, LST_KURS.LKU_SYMBOL FROM lst_prodset_calc join LST_KURS WHERE lst_prodset_calc.LKU_ID = LST_KURS.LKU_ID AND lst_prodset_calc.PSET_ID = :psetId',
            variables: [Variable.withInt(psetId)],
            readsFrom: {lstKurs, lstProdsetCalc}).map((QueryRow row) {
          return KursSymbol(
            lkuId: row.readString('LKU_ID'),
            lkuSymbol: row.readString('LKU_SYMBOL'),
          );
        }).get();
      }