如下model如何多表join? from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Table1(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) class Table2(db.Model): id = db.Column(db.Integer, primary_key=True) table1_id = db.Column(db.Integer) table3_id = db.Column(db.Integer) class Table3(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50))
时间: 2024-02-24 13:54:26 浏览: 33
To join multiple tables, you can use the `join()` method provided by SQLAlchemy. Here's an example of how you can join `Table1`, `Table2` and `Table3` based on their foreign key relationships:
```
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Table1(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
class Table2(db.Model):
id = db.Column(db.Integer, primary_key=True)
table1_id = db.Column(db.Integer, db.ForeignKey('table1.id'))
table3_id = db.Column(db.Integer, db.ForeignKey('table3.id'))
table1 = db.relationship('Table1', backref='table2')
table3 = db.relationship('Table3', backref='table2')
class Table3(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
# Join Table1, Table2 and Table3
result = db.session.query(Table1, Table2, Table3).\
join(Table2, Table1.id == Table2.table1_id).\
join(Table3, Table2.table3_id == Table3.id).all()
```
In this example, we first define the foreign key relationships between `Table1`, `Table2` and `Table3`. Then, we use the `join()` method to join these tables based on their foreign keys. Finally, we execute the query using `all()` to retrieve all the rows from the result set.
Note that you can also use the `filter()` method to filter the result set based on certain conditions.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)