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