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

猜你喜欢

转载自www.cnblogs.com/YC-L/p/12640196.html
今日推荐