技巧:模型查询的all()方法,第一个参数传入条件,第二个参数传入with关联的方法,如下片段:
class UserDirectTeam extends UserDirectTeamModel
{
public function toName()
{
return $this->hasOne('User', 'user_id', 'direct_user_id')->field('user_id,login_name as name');
}
public function getDirectTeam($where)
{
return $this::all($where,'toName')->toArray();
}
}
有表:content和表play
content表字段
id title
play表字段
id content_id play
play表中的content_id对应content表中的id
那么查询content表中关联的play表中的play字段,那么可以在thinkphp5的model中可以这样设置
class Content extends Model
{
protected $table = 'content';
public function play()
{
return $this->hasOne("Play", "content_id", "id")->field("play");
}
}
play表的模型为:
class Play extends Model
{
protected $table = 'play';
}
thinkphp5中的model里的hasOne的参数说明如下:
hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
以表content和表play来说
表content中的hasOne:
第一个参数为关联表play的模型名:play
第二个参数为关联表play的外键名:content_id
第三个参数为主表content关联表play的键名:id