3

I have the following flutter moor query

(select(recipeGarnishes)..where((tbl) => tbl.postGarnish.equals(true))).get();

How would I add the distinct condition to the query?

Update: The query I want to write is:

select DISTINCT garnishName from RecipeGarnishes where postGarnish = 'true'

garnishName and postGarnish are columns in my RecipeGarnishes table

Update 2:

Based on the answer, I tried this.

final query = selectOnly(recipeGarnishes, distinct: true)
                ..addColumns([recipeGarnishes.garnishName])
                ..where(recipeGarnishes.postGarnish.equals(postGarnish));
List<TypedResult> result = await query.get();

return result.map((row) => row.readTable(recipeGarnishes)).toList();

But it gives me the following error

Moor: Sent SELECT DISTINCT recipe_garnishes.garnish_name AS "recipe_garnishes.garnish_name" FROM recipe_garnishes WHERE recipe_garnishes.post_garnish = ?; with args [1]

[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter 'garnishName' was called on null.

Community
  • 1
  • 1
DrkStr
  • 1,752
  • 5
  • 38
  • 90

2 Answers2

8

The query itself is correct, but you can't read the result like that: row.readTable would return a full row with all columns. However, you only select a single column (garnishName), so moor can't load the row and returns null instead.

You can use

final query = selectOnly(recipeGarnishes, distinct: true)
                ..addColumns([recipeGarnishes.garnishName])
                ..where(recipeGarnishes.postGarnish.equals(postGarnish));

return query.map((row) => row.read(recipeGarnishes.garnishName)).get();
simolus3
  • 286
  • 1
  • 6
1

You can add distinct as follows

(select(recipeGarnishes, distinct: true)..where((tbl) => tbl.postGarnish.equals(true))).get();
prasad bankar
  • 46
  • 1
  • 4
  • I need to add distinct condition to the garnishName column, not the entire row. – DrkStr Jun 09 '20 at 08:13
  • For getting only particular columns, you can use selecyOnly instead of select, and using addColumns method. Otherwise, you can also use customSelect to enter your own query. – prasad bankar Jun 10 '20 at 08:53
  • Hi, I updated my question with the selectOnly. Still getting an error :( – DrkStr Jun 11 '20 at 12:40