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 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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