TP6.0 一对多模型关联 hasMany

本文测试关联方法都采用预载入查询

$data = Article::with('comments')->select();
halt($data->toArray());

1. 创建数据表


-- 文章表
CREATE TABLE `article` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `content` text,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `article` VALUES (1, 'PHP数据类型', '文章内容01');
INSERT INTO `article` VALUES (2, 'Java常量池', '文章内容02');
INSERT INTO `article` VALUES (3, 'Vue Cli 4 引入图片地址', '文章内容03');

-- 文章评论表
CREATE TABLE `comments` (
  `id` int(255) NOT NULL AUTO_INCREMENT COMMENT '评论ID',
  `article_id` int(11) DEFAULT NULL COMMENT '文章ID',
  `content` varchar(500) DEFAULT NULL COMMENT '评论内容',
  `create_time` int(11) DEFAULT NULL COMMENT '评论时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `comments` VALUES (1, 1, '作者文采太好了', 1597560224);
INSERT INTO `comments` VALUES (2, 1, '说的太对了', 1597560224);
INSERT INTO `comments` VALUES (3, 2, '这篇文章真不错,值得收藏', 1597560224);

2. 文章模型定义一对多关联方法


public function comments()
	{
		/**
		 * hasMany('关联模型', '关联模型外键','当前模型主键');
		 * Comments 评论模型
		 * article_id 评论表的外键字段,关联模型外键
		 * id 文章表主键字段,当前模型主键
		 */
		return $this->hasMany(Comments::class, 'article_id', 'id');
	}

3. hasMany() 支持的额外方法


  • 不支持 bind() 绑定关联属性到模型,因为结果是二维数组,所以不支持

  • 支持 hidden() 隐藏指定的关联属性

public function comments()
{
	return $this->hasMany(Comments::class, 'article_id', 'id')
		->hidden(['create_time', 'content']);
}

posted @ 2020-08-17 08:46  辰风沐阳  阅读(1658)  评论(0编辑  收藏  举报