Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: joining tables

Assume that the data look like this

post: {
  authorId: '123AA',
  title: 'first Post',
  body: 'yay'
}

author: {
  uid: '123AA',
  displayName: 'Richard'
  email: '[email protected]'
}

I want to render a post with the author's name:

<div className="post">
  <div className="title">{post.title}</div>
  <div className="body">{post.body}</div>
  <div className="author-name">{post.author.displayName}</div> //problem
</div>

A fetched post item only contains an author's uid, but I need the author's displayName. How do I populate the author field when retrieving the posts? This is what I do to fetch the posts right now:

const postsRef = firebase.database().ref('posts/')
postsRef.on('value', (snapshot) => {
  this.setState({posts: snapshot.val()})
})
like image 924
Maximus S Avatar asked Aug 05 '16 12:08

Maximus S


People also ask

Can we store tables in Firebase?

All Firebase Realtime Database data is stored as JSON objects. You can think of the database as a cloud-hosted JSON tree. Unlike a SQL database, there are no tables or records.

What is a joining table?

A join table is a data table that has multiple outgoing connections - connecting multiple data tables to one data table.

Can Firebase be used with SQL?

Firebase / Firestore + SQL Server IntegrationsZapier lets you send info between Firebase / Firestore and SQL Server automatically—no code required. Triggers when a new child object is discovered within a specific path. automatically do this! Adds a new row.


1 Answers

Not sure in real firebase, but I use join quite often in angular2. Here my sample code.

import { Component, OnInit } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map';

@Component({
  selector: 'app',
  templateUrl: `
    <ul>
        <li *ngFor="let p of posts | async">
            {{ p.title }} - {{ (p.authorName | async)?.displayName }}
        </li>        
    </ul>
`
})
export class InitComponent implements OnInit {
    posts: Observable<any[]>;

  constructor(private af: AngularFire) {}

  ngOnInit() {
      this.posts = this.af.database.list('/posts')
      .map(posts => {
          posts.map(p => {
              p.authorName = this.af.database.object('/authors/'+p.authorId);
          });
          return posts;
      });
  }

The database structure as follows:

/posts/postId/{authorId, title, body}
/authors/authorId/{displayName, email}

Hope this helps

like image 109
codetinker Avatar answered Oct 21 '22 22:10

codetinker