Comments (33)
Here’s an example:
Say you have two classes Author and Book. An Author can have many books.
In this case, the Book class would contain the Author object. like this:
class Book{
String name;
Author author;
}
class Author{
String name;
public List<Book> getBooks(){
return Book.find(Book.class, "author = ?", new String{author.getId()})
}
}
You can achieve the one to many relationship like this.
from sugar.
@satyan Thanks, your example helped me to understand how to implement oneToMany relationships ! I suggest you to maybe add this on your doc as it is not so clear how to implement it, I struggled a bit before I found this issue !
from sugar.
Many to many is slightly tricky.
You could create a LinkerClass similar to the link table in database, and use that to link the two objects.
eg:
Book
Author
AuthorBooks
where AuthorBooks would be
class AuthorBooks{
Author author;
Book book;
}
you can fetch in a similar style then:
List<AuthorBooks> authorBooks = AuthorBooks.find(AuthorBooks.class, “author = ?”, author.getId());
This would have the list of books.
It’s a round about approach.. but so far there’s no direct support for many to many relationship.
from sugar.
I don't understand the example - I'm using 1.4, but the code won't compile.
class Book{
String name;
Author author;
}
class Author{
String name;
public List<Book> getBooks(){
return Book.find(Book.class, "author = ?", new String{author.getId()})
}
}
The "author.getId()" always says "cannot resolve symbol". This example seems very incomplete - neither class extends SugarRecord, and author and getId() are not visible symbols within the Author class. Am I missing something here?
Also, if I switch the anonymous String to an anonymous string array
new String[]{author.getId()})
That returns a long, not a string. Syntax errors abound.
from sugar.
@MisterSpicy, please try this:
class Book extends SugarRecord<Book> {
String name;
Author author;
}
class Author extends SugarRecord<Author> {
String name;
public List<Book> getBooks(){
return Book.find(Book.class, "author = ?", String.valueOf(this.getId()))
}
}
from sugar.
I never would have thought that I needed to check to see if a highly regarded ORM supported one-to-many relationships. This is absolutely crucial. Is there ever going to be an update to support this?
from sugar.
I'm want understand how to make relationship one-to-many too. I try
private ArrayList images;
but this method doesn't work.
E/Sugar﹕ Class cannot be read from Sqlite3 database.
from sugar.
ArrayList or other collections aren't supported yet. You could define your relationship like this example: http://satyan.github.io/sugar/creation.html#why
from sugar.
I'm not sure based on the docs posted how to create a one to many relationship. Could you elaborate?
from sugar.
I've hit this roadblock also. Struggling with this one!
from sugar.
Any chance of this being supported soon? Or does anyone recommend any other ORM for Android?
from sugar.
Is this being worked on currently?
from sugar.
Sugar does not handle many to many relationship for you currently. You'd have to manage the relationship yourself using an approach suggested above #60 (comment)
It's not worked upon currently. Would love to hear some suggestions on this..
from sugar.
I'd definitely like to help if I can. Would you mind chatting a bit via email? I sent you one a few minutes ago before I stumbled upon this ticket.
from sugar.
+1 on the suggestion of @OlivierRevial to add the example on the documentation!
from sugar.
yes, +1 on adding that to the documentation! i was struggling with this for hours because i didnt know that Collections aren't supported
from sugar.
What about one to many relationships? Are this being worked on?
from sugar.
An book can have many Authors how to insert the values in this condition ?
class Book{
String name;
Author author;
public List<Author> getAuthors{
return Author.find(Book.class, "name = ?", new String{author.getName()})
}
}
class Author{
String name;
...
}
above code is correct ?
To-Many lists Relations?
One more thing how to insert the list of (array/Arraylist) values to One To Many relationship? (like mentioned in GreenDAO http://greendao-orm.com/documentation/relations/)
code from AddNoteActivity of Samples
Tag tag = new Tag(tagBox.getText().toString());
save(tag);
save(new Note(10 + (int) (10 * Math.random()), titleBox.getText().toString(), descBox.getText().toString(), tag));
How to save if there are list of many tags to the note?
List<Tag> taglist=new ArrayList<Tag>();
taglist.add(new Tag("Tagname")):
.
.
.
Tag tag = new Tag(taglist);
save(tag);
save(new Note(10 + (int) (10 * Math.random()), titleBox.getText().toString(), descBox.getText().toString(), tag));
this Will work for inserting many tags to to a single note? or any other ways to achieve this?
from sugar.
Ah just ran into this solution, but wanted to share what I ended up doing, maybe it helps someone out:
- @ignore the actual list structure
- Add a String "listJson" or the likes that keeps a json representation of the list
- Make sure that listJson is in sync before calling save on the object
- in you getList() method restore the list structure from the listJson String if the structure is empty/null
Not the most efficient/clean way but works for me for now (using small lists). Hoping to see proper list support soon though!
from sugar.
Thanks Cuberob for the Info, I finally did it in the same way by storing the string in json format! but json/gson parsing while retrieving inserting will effect performance! GeenDAO have mentioned some solutions for this.. Need try that Ref: #195
from sugar.
This is definitely much needed functionality. Is there a way to pass values to the constructor for sugar orm? I know it needs the default constructor. If possible then we can build up the many - many lists by passing the parent_id to the child_id class. So on querying the parent, in the constructor you do the find all by parent_id and build that object in the parent.
from sugar.
This is a critical feature and it will go into 1.4.0.
from sugar.
Is this feature present in 1.4 beta release ?
from sugar.
@rdenadai Hey, thanks for that, I was pretty tired and a little frustrated. I also found the whole set of examples in the project, which implements things like you have. Hopefully the docs get updated soon for 1.4!
from sugar.
sorry,who can give me one full example about one-to-many?I'm always not successThanks
from sugar.
Documentation did not help guys. I tried more than 1 time to implement simple Relation One to Many without succes. Android crash every time saying: android.database.sqlite.SQLiteException: no such column: travelSugar (code 1): , while compiling: SELECT * FROM PLACE_SUGAR WHERE travelSugar = ? where travelSugar is like "author" in @MisterSpicy above comment
from sugar.
@multivoltage In Sugar your field(travelSugar) will be represented as 'travel_sugar' in the database. So try like this YourClass.find(YourClass.class,"travel_sugar = ?", "somthing");
from sugar.
I don't understand how the example is supposed to work when you can't store objects as parameters in sugar, I mean the one with the Book and the Author. I get an error "no such column: author (code 1)" which is exactly what I expected when I saw the example, am I missing something?
If I could store objects as parameters in the database I wouldn't need to use a one to many solution.
EDIT: I found my problem, I had a table with something like this "nameTable", but sugarORM automatically changes those kinds of names to "name_table", so I had to search for it that way.
from sugar.
@satyan So we will have a direct support for many-to-many relationship in 2.0.0 for sure?
from sugar.
Hello.
I am a little confused.
class Book extends SugarRecord<Book> {
String name;
Author author;
}
class Author extends SugarRecord<Author> {
String name;
public List<Book> getBooks(){
return Book.find(Book.class, "author = ?", String.valueOf(this.getId()))
}
}
This code is really needed?
public List<Book> getBooks(){
return Book.find(Book.class, "author = ?", String.valueOf(this.getId()))
}
Thank you for helping me.
from sugar.
public String venueId;
public String venueName;
public String venueType;
public List < String > profileImages = new ArrayList < String > ();
this is my response model keys.. what should i do so that i can store that profileImages array in my database using SugarORM v1.5?
if any one can help please reply me , thank you
from sugar.
I'm having save issue with one to many relationship.
The example here http://satyan.github.io/sugar/creation.html#why is too vague and it also seems that @OneToMany annotation is removed in 1.5 release.
from sugar.
If someone can help. I have a similar kind of issue.. https://stackoverflow.com/questions/45389403/sugarorm-not-saving-object-inside-arraylist
from sugar.
Related Issues (20)
- Support for user specified ID's being used in the database instead of having them generated automatically.
- Android Studio 3.2.1 DB is no longer created HOT 3
- Is Sugar ORM library affected by the newly found SQLite vulnerability?
- update bug HOT 1
- [QUESTION] Where I can find the CI service?
- OneToMany Annotation
- Missing saveAll() for nested Table
- How read existing DB from assets folder? HOT 1
- Como deletar todos os dados de uma tabela e depois verificar se a tabela está vazia? HOT 1
- No such table with migration HOT 2
- ava.lang.NoSuchMethodException: <init> []
- SugarRecord Read / write separation
- bulk data not inserted completely
- Caused by: android.database.sqlite.SQLiteException: no such table: HOT 5
- *.db file is empty, but in application all the lines are shown.
- RuntimeException on start
- 我使用save来保存数据但是数据当中设置了不可重复字段会对其进行覆盖
- build failed when sync graddle HOT 1
- no such column when select
- Could not resolve project :sugar
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from sugar.