用hasone,hasMany主键是当前表
用belongsTo主键是关联表。
当关联ID在主表(当前模型的表)的时候用belongsTo
当关联ID在附表的时候用hasone,hasmany
class Banner extends Model
{
public function items() { //建立一对多关联
return $this->hasMany('BannerItem', 'banner_id', 'id'); //关联的模型,外键,当前模型的主键
}
public static function getBannerByID($id)
{
$banner = self::with('items')->find($id); // 通过 with 使用关联模型,参数为关联关系的方法名
return $banner;
}
}
class BannerItem extends Model
{
protected $hidden = ['delete_time', 'update_time'];
/**
* 建立与 Image 表的关联模型(一对一)
* @return \think\model\relation\BelongsTo
*/
public function img() {
return $this->belongsTo('Image', 'img_id', 'id'); //关联模型名,外键名,关联模型的主键
}
}