在一個模型中,新建方法實現外鍵關聯
<?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();