tp5.1 多对多关联,添加中间表自动时间戳


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');


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM