Get Data from Two Tables Floor Flutter - database

I want to get data from two tables using floor in flutter, how can I do that?
this code for getting data from one table. this function inside database.g.dart:
Stream<List<Item>> getItems() {
return _queryAdapter.queryListStream(
'SELECT * FROM Item WHERE is_active = 1',
mapper: (Map<String, Object?> row) => Item(
id: row['id'] as int?,
item_id: row['item_id'] as String,
description: row['description'] as String,
salePrice: row['sale_price'] as double,
purchasePrice: row['purchase_price'] as double,
isActive: row['is_active'] as int),
queryableName: 'Item',
isView: false);
}
So the return will be Item objects but what if I have junction table from another tables and the command will be like this:
SELECT junctiont.*, item.*, client.*
FROM item
INNER JOIN junctiont
ON item.id = junctiont.item_id
INNER JOIN client
ON junctiont.client_id = client.id
How the function will be? and what will return?.

I found the answer by create new object to return the whole coming columns or you can return to list
#override
Stream<List<List>> getBillsMainInfo() {
return _queryAdapter.queryListStream(
'SELECT Bills.id, Biils.bill_number, Bills.total, Bills.datetime, Clients.name FROM Bills INNER JOIN Clients ON Bills.client_id = Clients.id WHERE Bills.is_active = 1',
mapper: (Map<String, Object?> row) => [
row['id'] as int,
row['bill_number'] as int,
row['datetime'] as String,
row['name'] as String,
row['total'] as double
],
queryableName: 'Bills',
isView: false);
}

Related

Can't delete an object with a certained value inside an array in firebase/firestore

So I am a building a member system and every member has an array points.
But I can't seem to delete an object when a person tries to remove this point.
users(collection) -
member(document) -
"id" . --fields
"username" . --fields
"userevents" . --array
[0]
"id"
"date"
"price"
[1]
"id"
"date"
"price"
deletePoint = (userId, pointId, date, price) => {
let docRef = this.db.collection('users').doc(userId);
docRef.update({
points: this.db.FieldValue.arrayRemove({
date: date,
id: pointId,
price: price,
}),
});
};
this.db is firebase.firestore()
According to the documentation when you're using arrayRemove you have to point directly to the field that you want to remove, not the content within said field so your example would become:
deletePoint = (userId, pointId, date, price) => {
let docRef = this.db.collection('users').doc(userId);
docRef.update({
points: this.db.FieldValue.arrayRemove("0"),
});
};
And this will delete the whole content of the field (id, date, price) with an index of 0.

LINQ : filter multiple string values - partial match - not full match as in multiple online examples

There are many good examples of searching multiple string values in LINQ e.g.
public static Product[] GetProducts(Guid[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Contains(p.ProductID)
select p).ToArray<Product>();
}
I have a list of Products that I need to match from a customer,
but I dont have an exact match - the Customers List Of Products contains my ProductID - but it is not exact - e.g.
Customer MyCompany
Description Description
Prod1XY Prod1
AProd2B Prod2
XXXProd3 Prod3
I thus cannot filter from the prodIDs [string array] because Prod1 does not contain Prod1XY
and thus cannot use the examples that are available.
How can I effectively change (reverse) the working examples
as to search CustomerProducts where it contains my Product Description please?
So to confirm : this is not a duplicate. The examples use the string[] x
input parameter and then searches:
where x.contains
I need help to get it : myProducts.Contains(x)
another online example modified to show the situation:
static void Main(string[] args) {
var table = new[] {
new { uid = 1 },
new { uid = 2 },
new { uid = 3 },
new { uid = 4 },
new { uid = 5 }
};
var stringarray = new[] { "1", "5", "10" };
var results = from xx in table
where table.Contains(stringarray)
select xx;
foreach (var result in results) {
Console.WriteLine("Result: " + result.uid.ToString());
}
}
It is not clear enough what you are trying to accomplish, but under assumption that you want to select all products where ProductID contains any value from specified list, it looks like that it:
public static Product[] GetProducts(string[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Any(id=>p.ProductID.Contains(id))
select p).ToArray<Product>();
}
Try this
public static Product[] GetProducts(string[] prodIDs)
{
return (
from p in GetProducts()
from q in prodIDs
where p.ProductID.IndexOf(q) > -1
select p)
.ToArray<Product>();
}

create a class Table for an inexisting table slick scala (Slick 3.0.0, scala)

Assume that we have a database which contains two tables: Coffee and Suppliers and we have their corresponding case classes and tables, just as in the documentation:
import scala.slick.driver.MySQLDriver.simple._
import scala.slick.lifted.{ProvenShape, ForeignKeyQuery}
// A Suppliers table with 6 columns: id, name, street, city, state, zip
class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
def id: Column[Int] = column[Int]("SUP_ID", O.PrimaryKey) // This is the primary key column
def name: Column[String] = column[String]("SUP_NAME")
def street: Column[String] = column[String]("STREET")
def city: Column[String] = column[String]("CITY")
def state: Column[String] = column[String]("STATE")
def zip: Column[String] = column[String]("ZIP")
// Every table needs a * projection with the same type as the table's type parameter
def * : ProvenShape[(Int, String, String, String, String, String)] = (id, name, street, city, state, zip)
}
// A Coffees table with 5 columns: name, supplier id, price, sales, total
class Coffees(tag: Tag) extends Table[(String, Int, Double, Int, Int)](tag, "COFFEES") {
def name: Column[String] = column[String]("COF_NAME", O.PrimaryKey)
def supID: Column[Int] = column[Int]("SUP_ID")
def price: Column[Double] = column[Double]("PRICE")
def sales: Column[Int] = column[Int]("SALES")
def total: Column[Int] = column[Int]("TOTAL")
def * : ProvenShape[(String, Int, Double, Int, Int)] = (name, supID, price, sales, total)
// A reified foreign key relation that can be navigated to create a join
def supplier: ForeignKeyQuery[Suppliers, (Int, String, String, String, String, String)] =
foreignKey("SUP_FK", supID, TableQuery[Suppliers])(_.id)
}
Now assume that we want to do a join:
val result = for {
c <- coffees
s <- suppliers if c.supID === s.id
} yield (c.name, s.name)
And here dealing with the result is complicated ( and it's more complicated if we have a lot of joins) because we need always to remember the order of names, to know what _._1 or _._2 refer to ... etc.
Question 1 Is there a way to change the type of the result as a table of a new class which contains the desired columns ?
Question 2 Here is a way but I can't finish it, we construct a case class for example:
case class Joined(nameS: String,nameC: String)
and after that we construct the corresponding table which I don't know how
class Joineds extends Table[Joinedclass] {
//Todo
}
and when we write a join we can write something like ( so that we can transform result to a type Joined) :
val result = for {
c <- coffees
s <- suppliers if c.supID === s.id
} yield (c.name, s.name).as(Joinds)
Thank you.
Can you define it like:
val result = for {
c <- coffees
s <- suppliers if c.supID === s.id
} yield Joined(c.name, s.name)
And the tuck it away in some convenient place?

Can Dapper handle dynamic column header

I have a stored procedure that always returns a list of strings. However, based on the parameters passed to the stored procedure, the column heading for the list of strings will change. Is Dapper able to handle this? If so, how should it be handled?
conn.Open();
var p = new DynamicParameters();
p.Add("Search_Function_CD", searchFunction, DbType.String, ParameterDirection.Input);
p.Add("Search_Value", searchValue, DbType.String, direction: ParameterDirection.Input);
p.Add("o_resultset", dbType: DbType.Object, direction: ParameterDirection.Output);
var Results = (IDictionary<string, object>)conn.Query(sql: CommonConstants.ProcedureConstants.PKG_GET_SEARCH_RESULTS, param: p, commandType: CommandType.StoredProcedure);
foreach (object o in Results)
{
string element = Results.Values.ElementAt(1) as string;
searchResults.Add(element);
}
conn.Close();
return searchResults;
You can get the value by a dynamic column name or index:
var row = (IDictionary<string, object>)con.Query("select * from Products").First();
string name = row["ProductName"]; // column name 'ProductName'
// or:
string name = row.Values.ElementAt(1) as string; // column index 1

How to count number of same data in a column

I have a table:
Id Catg
1 cat01
2 cat01
3 cat01
1 cat02
2 cat02
now I want to detect number of occurance of catg01 and catg02,like in this ex, catg01 is 3 times and catg02 is 2 times,I want to count that through LINQ/ simple db query.
Pls note: cant use Where clause and hardcode Catg01/catg 02,as there can n number of category.Is it possible to detect? if yes then pls help.
SELECT Catg, COUNT(*)
FROM myTable GROUP BY Catg
Select Catg, Count(*) From TableName Group By CatG
For the LINQ Version. Imagine a Class
class Table
{
public int ID { get; set; }
public string CatG { get; set; }
}
Then if you had a list of that class, you could query it as follows
List<Table> y = new List<Table>();
y.Add(new Table() { ID = 1, CatG = "a" });
y.Add(new Table() { ID = 2, CatG = "a" });
y.Add(new Table() { ID = 3, CatG = "a" });
y.Add(new Table() { ID = 4, CatG = "b" });
y.Add(new Table() { ID = 5, CatG = "b" });
var query = y.GroupBy(table => table.CatG);
// Iterate over each IGrouping in the collection.
foreach (var item in query)
{
Console.WriteLine("CatG: {0} Number of Items: {1}", item.Key, item.Count());
}

Resources