Bootstrap

TP5框架 之多对多关联

一、表设计

user表

group表

user_group表

二、模型设计

User模型

<?php

namespace app\index\model;

class Users extends \think\Model
{
    protected $pk = "id";

    protected $autoWriteTimestamp = "datetime";
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $createTime = "date_entered";

    /**
     * 获取群列表
     * @return \think\model\relation\BelongsToMany
     */
    public function groups()
    {
        return $this->belongsToMany("Groups", "user_group", "group_id", "user_id");
    }
}

Group模型

<?php

namespace app\index\model;

use think\Model;

class Groups extends Model
{
    protected $pk = "id";
    protected $autoWriteTimestamp = "datetime";
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $createTime = "date_entered";

    public function users()
    {
        return $this->belongsToMany("Users", "user_group", "user_id", "group_id");
    }
}

;