【ThinkPHP】5.1 完全开发手册 / 远程一对多

远程一对多

远程一对多关联用于定义有跨表的一对多关系,例如:

关联定义

就可以直接通过远程一对多关联获取每个城市的多个话题,City模型定义如下:

<?php
namespace app\index\model;

use think\Model;

class City extends Model 
{
public function topics()
{
return $this->hasManyThrough('Topic','User');
}
}

远程一对多关联,需要同时存在Topic和User模型。

hasManyThrough方法的参数如下:

hasManyThrough('关联模型','中间模型','外键','中间表关联键','主键');

关联查询

我们可以通过下面的方式获取关联数据

$city = City::get(1);
// 获取同城的所有话题
dump($city->topics);
// 也可以进行条件搜索
dump($city->topics()->where('topic.status',1)->select());

条件搜索的时候,需要带上模型名作为前缀