[AngularFire 2] Joins in Firebase

本文介绍如何在 Firebase 中设置索引并进行高效查询。首先通过在 Firebase 控制台中配置索引来加速查询过程,接着展示了如何使用 AngularFire 进行具体查询操作,包括按 URL 查找课程及获取课程的所有课程章节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lets see how to query Firebase.

 

First thing, when we do query, 'index' will always help, for both SQL and NoSQL. 

In Firebase, we can also set index on props, for example we want to set an 'index' on 'courses' --> 'url' prop, we will use 'url' to locate course object.

 

How to set up index?

In Firebase console --> database --> Rules:

We tell Firebase, for 'courses' document, we want to set index on 'url'.

 

After setting up index, then how can we do query?

  findCourseByUrl(courseUrl): Observable<Course>{
    return this.angularFire.database.list('courses', {
      query: {
        orderByChild: 'url',
        equalTo: courseUrl
      }
    })
    .map((courses) => courses[0]); // get courses document which url = courseUrl
  }

We need to pass 'query' object for searching course. Notice we are using 'orderByChild' and 'equalTo'.

 

Get courses' lessons:

  findAllCourseLessons(courseUrl){
    const course$ = this.findCourseByUrl(courseUrl);

    const lessonsPreCourse$ = course$
      .filter(course => !!course)
      .switchMap((course) => {
        console.log(course);
        return this.db.list(`lessonsPerCourse/${course.$key}`)
      });

    return lessonsPreCourse$
      .map((lessonKeys) => lessonKeys
          .map( (lessonKey) => {
             return this.db.object(`lessons/${lessonKey.$key}`)
          }))
      .flatMap((res) => {
        return Observable.combineLatest(res);
      });

  }

We have a document 'lessonsPreCourse' to maintain the lessons which course includes:

This is normalize the dataset, to avoid nest array.

After getting 'lessonsPreCourse', we are going to get all the lessons in 'lessons' document.

 

Then in the UI, we can use 'async' pipe to show the lessons:

<md-list>
  <md-list-item *ngFor="let lesson of lessons$ | async">
    <a *ngIf="lesson.hasVideoUrl" [href]="lesson.videoUrl">{{lesson.description}}</a>
    <span *ngIf="!lesson.hasVideoUrl">{{lesson.url}}</span>
  </md-list-item>
</md-list>
  ngOnInit() {
    if(this.route.snapshot.params['url']){
      const url = this.route.snapshot.params['url'];
      this.lessons$ = this.courseService.findAllCourseLessons(url);
    }
  }

 

Github

在 Flask SQLAlchemy 中,可以通过在查询中使用多个 `join()` 方法来实现多个表的关联查询。下面是一个示例代码: ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), nullable=False) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) user = db.relationship('User', backref=db.backref('posts', lazy=True)) class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.Text, nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False) post = db.relationship('Post', backref=db.backref('comments', lazy=True)) @app.route('/') def index(): query = db.session.query(Post, Comment, User).\ join(User).\ join(Comment).\ filter(User.username == 'john').\ all() return str(query) ``` 上面的代码中,我们定义了三个模型类 `User`、`Post` 和 `Comment`,并且在 `Post` 模型中定义了一个外键 `user_id`,在 `Comment` 模型中定义了一个外键 `post_id`。我们使用 `db.relationship()` 方法来定义了一个 `user` 属性和一个 `post` 属性,它们分别可以让我们通过 `post.user` 和 `comment.post` 来访问到这个 `Post` 对象所属的 `User` 对象和该评论所属的 `Post` 对象。 在视图函数中,我们使用 `db.session.query()` 方法来创建查询对象,然后使用多个 `join()` 方法来指定要关联的模型,最后使用 `filter()` 方法来添加查询条件。在这个例子中,我们查询所有属于用户名为 "john" 的用户所发表的文章和这些文章所对应的评论,最后关联到这些文章所属的用户。 注意,在使用多个 `join()` 方法时,我们需要注意表之间的关系,即在使用 `join()` 方法时,需要指定关联的属性名和关联的外键。如果关系比较复杂,可以使用 `join()` 方法的另一种语法 `join(User, Post.user_id == User.id).join(Comment, Post.id == Comment.post_id)` 这样的语法来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值