think 5.1 多對多關聯,有兩種方式:
方式一:
直接寫中間表名,進行關聯
格式:
return $this->belongsToMany('關聯模型名', '中間表名', '中間表外鍵,對應關聯模型主鍵', '當前模型關聯鍵,中間表中的字段對應當前模型的主鍵');
例:
return $this->belongsToMany('TemplateModel', 'user_template_related', 'template_id', 'user_id');
因為,中間表模型的基類Pivot
默認關閉了時間戳自動寫入,所以我們需要使用使用第二種方式
方式二:
創建中間表模型,進行關聯
例:
1.創建中間表模型
<?php
namespace app\common\model;
use think\model\Pivot;
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');