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

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

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
107
粉丝
44
喜欢
147
收藏
183
排名:299
访问:3.2 万
私信
所有博文
社区赞助商