本文測(cè)試關(guān)聯(lián)方法都采用預(yù)載入查詢(xún)
Article::with('comments')->select();
1. 創(chuàng)建數(shù)據(jù)表
-- 文章表
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數(shù)據(jù)類(lèi)型', '文章內(nèi)容01');
INSERT INTO `article` VALUES (2, 'Java常量池', '文章內(nèi)容02');
INSERT INTO `article` VALUES (3, 'Vue Cli 4 引入圖片地址', '文章內(nèi)容03');
-- 文章評(píng)論表
CREATE TABLE `comments` (
`id` int(255) NOT NULL AUTO_INCREMENT COMMENT '評(píng)論ID',
`article_id` int(11) DEFAULT NULL COMMENT '文章ID',
`content` varchar(500) DEFAULT NULL COMMENT '評(píng)論內(nèi)容',
`create_time` int(11) DEFAULT NULL COMMENT '評(píng)論時(shí)間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `comments` VALUES (1, 1, '作者文采太好了', 1597560224);
INSERT INTO `comments` VALUES (2, 1, '說(shuō)的太對(duì)了', 1597560224);
INSERT INTO `comments` VALUES (3, 2, '這篇文章真不錯(cuò),值得收藏', 1597560224);
2. 文章模型定義一對(duì)多關(guān)聯(lián)方法
public function comments()
{
/**
* hasMany('關(guān)聯(lián)模型', '關(guān)聯(lián)模型外鍵','當(dāng)前模型主鍵');
* Comments 評(píng)論模型
* article_id 評(píng)論表的外鍵字段,關(guān)聯(lián)模型外鍵
* id 文章表主鍵字段,當(dāng)前模型主鍵
*/
return $this->hasMany(Comments::class, 'article_id', 'id');
}
3. hasMany() 支持的額外方法
不支持
bind()
綁定關(guān)聯(lián)屬性到模型,因?yàn)榻Y(jié)果是二維數(shù)組,所以不支持支持
hidden()
隱藏指定的關(guān)聯(lián)屬性
public function comments()
{
return $this->hasMany(Comments::class, 'article_id', 'id')
->hidden(['create_time', 'content']);
}