vuex-orm: Why vuex-orm returns null in relationship field?
I followed the guide of Defining Relationships in Vuex ORM.
I did everything like the guide, so why I get null value in the category field in Article Model?
This is how I defining my models (category on article is: hasOne/belongTo):
export class Category extends Model {
static entity = "categories";
static primaryKey = "_id";
static fields() {
return {
_id: this.attr(null),
name: this.attr("")
};
}
}
export class Article extends Model {
static entity = "articles";
static primaryKey = "_id";
static fields() {
return {
_id: this.attr(null),
name: this.attr(""),
category: this.hasOne(Category, "_id")
};
}
Config Vuex-orm with vuex in main.js:
import VuexORM from "@vuex-orm/core";
import { Article, Category } from "./models";
Vue.use(Vuex);
const database = new VuexORM.Database();
const Articles = {
namespaced: true,
actions: {
test() {
console.log(this);
}
}
};
const Categories = {
namespaced: true,
actions: {
test() {
console.log(this);
}
}
};
database.register(Article, Articles);
database.register(Category, Categories);
const store = new Vuex.Store({
plugins: [VuexORM.install(database)]
});
Inside app component I have the data that I insert to vuex and get the values like so:
const articleData = [
{
_id: "6ce9bae00000000000000000",
name: "article-1",
category: "5ce9acd00000000000000000"
}
];
const categoryData = [
{ _id: "5ce9acd00000000000000000", name: "category-1" }
];
const x = await Article.insertOrUpdate({ data: articleData });
const y = await Category.insertOrUpdate({ data: categoryData });
const a = Article.query()
.with("category")
.first();
console.log({ a });
console.log({ type: a.category });
console.log("why a.category is null???");
I have been trying to understand this for several days without success. I would much appreciate any help.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 1
- Comments: 24 (23 by maintainers)
Hi !
Try with this model definition:
You then need to use
category_idin App.vue.It happens to me too to be confused. Especially because in the docs it’s in the One to One section. I’m sure we can improve this.
Hope it helps !!
It is already working as expected. So you want to fetch posts “with” user (author) right? If so you should be doing this. https://codesandbox.io/embed/vue-template-s3cof
Like this. https://codesandbox.io/embed/vue-template-hpp7e
ohhhh, I updated again with
Post.query().with('author').get(), it’s working@emahuni Hi! Thanks for the code. But this is expected. Within store, the relationship field should be
nullor empty array. In your example, theauthorfield should always be null inside store.Are you having trouble loading the relationship…? Then you must fetch data by
withquery chan.With above code, you’ll get all Post with related User nested.