laravel 模型多对多,应用

laravel 模型多对多,应用,试卷 跟 区域 多对多关系

一个试卷可以发放到a b c 区域
  1. 创建试卷表
CREATE TABLE `exams` (
  `exam_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `exam_title` varchar(100) NOT NULL DEFAULT '' COMMENT '标题',
  `created_time` int(11) NOT NULL DEFAULT '0',
  `updated_time` int(11) NOT NULL,
  PRIMARY KEY (`exam_id`) USING BTREE
  1. 创建区域表
CREATE TABLE `area` (
  `area_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `area_name` varchar(100) NOT NULL DEFAULT '' COMMENT '标题',
  `parent_id` int(10) NOT NULL DEFAULT '0' COMMENT '父级ID\n',
  `created_time` int(11) NOT NULL DEFAULT '0',
  `updated_time` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`area_id`) USING BTREE
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
  1. 创建区域跟试卷表的多对多关系表
CREATE TABLE `zt_exam_id_with_area_id` (
  `with_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `exam_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '试卷id',
  `area_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '区域id',
  PRIMARY KEY (`with_id`) USING BTREE,
  KEY `exam_id_with_area_id_index` (`exam_id`) USING BTREE
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='试卷跟区域关联关系,多对多';
  1. exams 模型 简历 跟 area 多对多的关系
    public function areaIds()
    {

        $DB_PREFIX = env('DB_PREFIX');
        return $this->belongsToMany(Area::class, 'exam_id_with_area_id', 'exam_id', 'area_id')
            ->select(DB::raw("DISTINCT({$DB_PREFIX}area.`area_id`),`{$DB_PREFIX}area`.*"));
    }

. 1.通过中间表:exam_id_with_area_id 建立 试卷 跟 区域的多对多关系

  1. 调用 exam模型的对对多方法
$model = new exams模型()
primary_key = ”exams模型表自增主键 对应的值 如:1“
$detail  = $model->find($primary_key)
$detail->areaIds->toArray();
返回试卷为1:对应可以发放的试卷信息列表

$detail->areaIds->toArray(); 转为 具体的 demo sql:

 select * from area  as a inner join exam_id_with_area_id  wi on a.area_id=wi.area_id where exam_id=1
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值