一对多关联

一对多关联

关联定义

一对多关联的情况也比较常见,使用hasMany方法定义,
参数包括:

hasMany('关联模型名','外键名','主键名',['模型别名定义']);

例如一篇文章可以有多个评论

namespace app\index\model;

use think\Model;

class Article extends Model 
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

同样,也可以定义外键的名称

namespace app\index\model;

use think\Model;

class Article extends Model 
{
    public function comments()
    {
        return $this->hasMany('Comment','art_id');
    }
}

如果需要指定查询字段,可以使用下面的方式:

namespace app\index\model;

use think\Model;

class Article extends Model 
{
    public function comments()
    {
        return $this->hasMany('Comment')->field('id,author,content');
    }
}

关联查询

我们可以通过下面的方式获取关联数据

$article = Article::get(1);
// 获取文章的所有评论
dump($article->comments);
// 也可以进行条件搜索
dump($article->comments()->where('status',1)->select());

根据关联条件查询

可以根据关联条件来查询当前模型对象数据,例如:

// 查询评论超过3个的文章
$list = Article::has('comments','>',3)->select();
// 查询评论状态正常的文章
$list = Article::hasWhere('comments',['status'=>1])->select();

关联新增

$article = Article::find(1);
// 增加一个关联数据
$article->comments()->save(['content'=>'test']);
// 批量增加关联数据
$article->comments()->saveAll([
    ['content'=>'thinkphp'],
    ['content'=>'onethink'],
]);

定义相对的关联

要在 Comment 模型定义相对应的关联,可使用 belongsTo 方法:

name app\index\model;

use think\Model;

class Comment extends Model 
{
    public function article()
    {
        return $this->belongsTo('article');
    }
}
posted @   徐锅  阅读(187)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南

点击右上角即可分享
微信分享提示