tp5模型一對一關聯hasOne


在一個模型中,新建方法實現外鍵關聯

<?php
namespace app\user\model;

use think\Model;

class GridmanReportLogs extends Model
{
    protected $table = 'sq_gridman_report_logs';
    protected $pk = 'id';
    protected $resultSetType = 'collection';

    public function reportTypeName()
    {
        return $this->hasOne('GridmanReportType', 'id', 'report_type_id')->bind('report_type');
    }

    public function user()
    {
        return $this->hasOne('Users', 'id', 'user_id')->bind('name');
    }
}
  • hasOne(關聯模型,關聯模型主鍵,當前模型外鍵)
  • bind('name'),將關聯模型得name屬性綁定到當前模型

 通過with關聯表使用該方法

$this->gridmanReportLogs->with('user', 'LEFT')->where('user_id', $userId)->select();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM