表关联操作

ActiveRecord 天然支持表关联操作,并不需要学习新的东西,此为无招胜有招。表关联操作主要有两种方式:一是直接使用 sql 得到关联数据;二是在 Model 中添加获取关联数据的方法。

假定现有两张数据库表:user、blog,并且 user 到 blog 是一对多关系,blog 表中使用 user_id 关联到 user 表。如下代码演示使用第一种方式得到 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 中获取相关联的 User 以及在 User 中获取相关联的 Blog:

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

    public User getUser() {
       return User.dao.findById(get("user_id"));
    }
}

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

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

上面代码在具体的 Model 中 new 了一个 dao 对象出来,这种用法仅用于表关联操作,其它情况的 dao 对象应该让 Service 层持有。