本文測試關聯方法都采用預載入查詢
$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']);
}