How can I join 3 tables and output all three together joined in web2py?

南楼画角 提交于 2019-12-11 22:40:14

问题


model:

# coding: utf8
db.define_table('dept',
                Field('name',unique=True,label='Department Name'),
                format='%(name)s')

db.define_table('course',
                Field('dept_id','reference dept'),
                Field('name',unique=True,label='Course Name'),
            format='%(name)s')

db.define_table('files',
                Field('course_id', 'reference course'),
                Field('documentx','upload'))

controller:

def show_doc():
    rows = db( db.course.id == db.files.course_id , db.dept.id==db.course.dept_id).select()
    return rows

What I am trying to do is to join the department table "dept" with the "course" table and the "course" table with the "files" table. So when outputting it shows a table with department with course and files all together. The solution doesn't work. It only creates a join between the "course" table and the "files" table.


回答1:


As noted in the book, it should be:

db((db.course.id == db.files.course_id) & (db.dept.id==db.course.dept_id))



回答2:


In your controller, you can simply select all your files :

def show_doc():
    rows = db(db.files.documentx).select()
    return dict(rows=rows)

Then, in your view "show_doc.html" you can access to the linked fields :

{{extend 'layout.html'}}
{{for row in rows:}}
    <div>Department : {{=row.course_id.dept_id.name}} Course : {{=row.course_id.name}}</div>
    {{if row.documentx:}}
        <div><a href={{=URL('default', 'download', args=row.documentx)}}>Download file</a></div>
    {{pass}}
    <hr>
{{pass}}


来源:https://stackoverflow.com/questions/20697034/how-can-i-join-3-tables-and-output-all-three-together-joined-in-web2py

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!