Firebase:连接表格 [英] Firebase: joining tables
问题描述
post:{
authorId:'123AA',
title:'first post',
body:'yay'
}
作者:{
uid:'123AA',
displayName:' Richard'
email:'im@richard.com'
}
I
< div className =post>想要使用作者的名字来显示帖子:
< div className =title> {post.title}< / div>
< div className =body> {post.body}< / div>
< div className =author-name> {post.author.displayName}< / div> //问题
< / div>
取得的项目只包含作者的 uid
,但是我需要作者的 displayName
。检索帖子时如何填充作者字段?这是我现在要做的职位:
$ p $ const postsRef = firebase.database()。ref('posts / ')
postsRef.on('value',(snapshot)=> {
this.setState({posts:snapshot.val()})
})
在真实的firebase中不确定,但我经常在angular2中使用join。这里我的示例代码。
$ b
从'@ angular / core'导入{Component,OnInit};
从'angularfire2'导入{AngularFire};
从'rxjs / Observable'导入{Observable};
导入'rxjs / add / operator / map';
@Component({
selector:'app',
templateUrl:`
< ul>
< li * ngFor =let p | async>
{{p.title}} - {{p.authorName | async)?displayName}}
< / li>
< / ul> ;
`
})
export class InitComponent implements OnInit {
posts:Observable< any []>;
构造函数(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 );
});
返回信息;
});
数据库结构如下:
pre $ / posts / postId / {authorId,title,body}
/ authors / authorId / {displayName,email}
希望这有助于
Assume that the data look like this
post: {
authorId: '123AA',
title: 'first Post',
body: 'yay'
}
author: {
uid: '123AA',
displayName: 'Richard'
email: 'im@richard.com'
}
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()})
})
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
这篇关于Firebase:连接表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!