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

Laravel框架
416
0
0
2022-12-10

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’)