table association operations
JFinal ActiveRecord naturally supports table association operations, and there is no need to learn new things. This is a win-win situation. There are two main methods for table association operations: one is to directly use sql to obtain associated data; the other is to add a method to obtain associated data in the Model.
Assume that there are two existing database tables: user and blog, and there is a one-to-many relationship from user to blog, and the blog table is related to the user table using user_id. The following code demonstrates using the first method to obtain user_name:
##public void relation() {
String sql = "select b .*, u.user_name from blog b inner join user u on b.user_id=u.id where b.id=?";
Blog blog = Blog.dao.findFirst(sql, 123); String name = blog .getStr("user_name");
}
Blog blog = Blog.dao.findFirst(sql, 123); String name = blog .getStr("user_name");
}
public class Blog extends Model<Blog>{
public static final Blog dao = new Blog();
public User getUser() {
return User.dao.findById(get("user_id"));
}
}
public class User extends Model<User>{
public static final User dao = new User();
public List<Blog> getBlogs() {
return Blog.dao.find("select * from blog where user_id=?", get("id")) ;
}
}
public User getUser() {
return User.dao.findById(get("user_id"));
}
}
public class User extends Model<User>{
public static final User dao = new User();
public List<Blog> getBlogs() {
return Blog.dao.find("select * from blog where user_id=?", get("id")) ;
}
}
##