think 5.1 多对多关联,有两种方式:
方式一:
直接写中间表名,进行关联
格式:
return $this->belongsToMany('关联模型名', '中间表名', '中间表外键,对应关联模型主键', '当前模型关联键,中间表中的字段对应当前模型的主键');
例:
return $this->belongsToMany('TemplateModel', 'user_template_related', 'template_id', 'user_id');
因为,中间表模型的基类Pivot
默认关闭了时间戳自动写入,所以我们需要使用使用第二种方式
方式二:
创建中间表模型,进行关联
例:
1.创建中间表模型
<?php
namespace appcommonmodel;
use thinkmodelPivot;
class UserTemplatePivotModel extends Pivot
{
protected $table = 'user_template_Pivot';
protected $autoWriteTimestamp = true;
}
2.使用关联
格式:
return $this->belongsToMany('关联模型名', '中间表模型,要带命名空间', '中间表外键,对应关联模型主键', '当前模型关联键,中间表中的字段对应当前模型的主键');
例:
return $this->belongsToMany('TemplateModel', '\app\common\model\UserTemplatePivotModel', 'template_id', 'user_id');