关于关联查询的记录

技巧:模型查询的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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值