讨论 技术讨论 Laravel 中模型关联的几种用法总结

Laravel 中模型关联的几种用法总结

Alan 发表于    阅读:383    回复:0

Laravel 中的模型关联为我们使用带来了极大遍历,今天总结一下几种常见的模式和用法。

一对多

举例说明,Post ↔ Comment

class Post extends Model {    public function comments() {        return $this->hasMany(Comment::class);
    }
}class Comment extends Model {    public function post() {        return $this->belongsTo(Post::class);
    }
}

执行 SQL 数量

如果使用 with 时,会一个查询会拆解为两个 SQL,一个是查找 Post,一个是查找 Comment(该查找使用的是 select in 方法,多个 Post 只执行一次 Comment 的查询工作)

用法(使用 with

$comments = Post::with('comments')->find(1)->comments

用法(使用 load

$post = Post::find(1)

$post->load('comments')

load 是对已经查出的模型使用,with 是直接做好关联关系的查询,两者查询的 sql 是一样的 。

多对多

举例说明,User``` ↔ ```Role

class Role extends Model {
}class User extends Model {    public function roles() {        return $this->belongsToMany(Role::class, 'user_role', 'roleId', 'userId');
    }
}

用法(使用 with

$roles = User::with('roles')->find(1)->roles;

用法(使用 load

$user = User::find(1);

$user->load('roles');

load 是对已经查出的模型使用,with 是直接做好关联关系的查询,两者查询的 sql 是一样的 。

一对一

举例说明,User ↔ Profile

class User extends Model {    public function profile() {        return $this->hasOne(Profile::class,'id');
    }
}class Profile extends Model {
}

用法(使用 with

$user = User::with('profile')

我来评论
QQ
微信