<?php
declare (strict_types = 1);
namespace app\controller;
use think\Request;
use app\model\Article;
class Test
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
// 查询用户及其文章
$Articles = Article::with('posts')->select()->toArray();
dd($Articles);
// 使用has()方法,查询关联附表的主表内容,***比如大于等于2条的主表记录,这个也相当于反向查询了,从附表推出主表数据
// $Articles = Article::has('posts','>=',2)->select()->toArray();
// dd($Articles);
// 关联删除
// 在删除文章的同时删除下面的评论
// $Articles = Article::with('posts')->find(2);
// $Articles->together(['posts'])->delete();
// dd($Articles);
}
}
<?php
declare (strict_types = 1);
namespace app\model;
use think\Model;
/**
* @mixin \think\Model
*/
class Article extends Model
{
// 定义一对多关联
public function posts()
{
// hasMany('关联模型','外键','主键');
//关联模型(必须):关联模型类名
//外键:关联模型外键,默认的外键名规则是当前模型名+_id,如:Comments表的article_id
//主键:当前模型主键,一般会自动获取也可以指定传入,如:Article 表的id
return $this->hasMany('Comments', 'article_id');
}
}
<?php
declare (strict_types = 1);
namespace app\model;
use think\Model;
/**
* @mixin \think\Model
*/
class Comments extends Model
{
// 在model中隐藏不想显示的字段
protected $hidden = ['article_id'];
// 定义多对一关联
// public function user()
// {
//https://www.choudalao.com/article/43
// return $this->belongsTo('Article');
// }
}
数据库表结构:
article表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for article
-- ----------------------------
DROP TABLE IF EXISTS `article`;
CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of article
-- ----------------------------
INSERT INTO `article` VALUES (1, '文章1', '文章1内容');
INSERT INTO `article` VALUES (2, '文章2', '节省空间打开手机');
INSERT INTO `article` VALUES (3, '这是第三篇文章', '继续卷啊');
SET FOREIGN_KEY_CHECKS = 1;
comments表:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for comments
-- ----------------------------
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) NULL DEFAULT NULL,
`content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of comments
-- ----------------------------
INSERT INTO `comments` VALUES (1, 1, '评论:第一篇');
INSERT INTO `comments` VALUES (2, 1, '评论:第一篇的第二个评论');
INSERT INTO `comments` VALUES (3, 3, '评论:第三篇');
INSERT INTO `comments` VALUES (4, 2, '第二文章的评论');
SET FOREIGN_KEY_CHECKS = 1;
运行结果: