cfmy

1. 创建数据表


一对一反向关联使用率很高

附表关联主表称为反向关联,又称为相对关联(tp官方手册这样叫)

-- 分类表
CREATE TABLE `category` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT \'主键id\',
  `name` varchar(255) DEFAULT NULL COMMENT \'分类名称\',
  `sort` int(11) DEFAULT NULL COMMENT \'分类排序\',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `category` VALUES (1, \'Java\', 0);
INSERT INTO `category` VALUES (2, \'Vue\', 0);

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

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


public function category()
{
	/**
	 * belongsTo(\'关联模型\', \'当前模型外键\', \'关联模型主键\');
	 *
	 * 第一个参数
	 * app\model\Category 关联的模型类名(分类表模型)
	 *
	 * 第二个参数
	 * category_id 外键字段,默认的外键名规则是关联模型名+_id(文章表外键字段)
	 *
	 * 第三个参数
	 * id 关联模型主键,默认是关联模型的 $pk 值(分类表主键字段)
	 */
    return $this->belongsTo(Category::class, \'category_id\', \'id\');
}

3. belongsTo() 也支持额外的方法 同 hasOne()


public function category()
{
	/**
	 * belongsTo(\'关联模型\', \'当前模型外键\', \'关联主键\');
	 */
    return $this->belongsTo(Category::class, \'category_id\', \'id\')->bind([
    	\'name\', \'sort\'
    ]);
}

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-05-22
  • 2021-09-08
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2021-08-09
  • 2021-09-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-01
  • 2022-12-23
  • 2022-12-23
  • 2018-11-10
  • 2021-05-23
相关资源
相似解决方案