Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

5.9 Table association operations


May 14, 2021 JFinal manual



JFinal ActiveRecord naturally supports table association operations and doesn't need to learn anything new. Table There are two main ways to associate: one is to use sql directly to get the associated data, and the other is to add a method in model to get the associated data.


Suppose you have two existing database tables: user, blog, and user-to-blog is a one-to-many relationship, and the blog table user_id to the user table. The following code demonstrates the first way to get 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");
}
The following code demonstrates the second way to get the associated User in the Blog and the associated blog in the User:

public class Blog extends Model<Blog>{
public static final Blog dao = new Blog();

public
User getUser() {
return U ser. dao .findById(get("user_id"));
}
}
public class User extends Model<User>{
public static final User dao = new User();

public
List<Blog> getBlogs() {
return B log. dao .find("select * from blog where user_id=?", get("id"));
}
}