简体   繁体   中英

List data from two table in tableView

How can I list data from two table in tableView?

Database (Example) Sqlite:

tb_sales
  tb_product
  tb_value
  tb_customer_id (Customer Id "tb_customer")

tb_customer
  tb_customer_id (id primary key)
  tb_name
  tb_state

With QSqlRelationalTableModel fetch only the client's name. Also need the state .

model= new QSqlRelationalTableModel(this); 
model->setTable("tb_sales");
model->setRelation(2, QSqlRelation("tb_customer", "tb_customer_id", "tb_name"));
model->select();
ui->tableView->setModel(model);

QSqlRelationalTableModel only allows you to include one column from the secondary table. You can use QSqlQueryModel to have a query in which you join the two tables :

QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT tb_sales.* , tb_customer.tb_name, tb_customer.tb_state FROM tb_sales LEFT JOIN tb_customer ON tb_sales.tb_customer_id = tb_customer.tb_customer_id");

ui->tableView->setModel(model);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM