123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- <?php
- namespace think\model\relation;
- use think\db\Query;
- use think\Exception;
- use think\Loader;
- use think\Model;
- use think\model\Relation;
- class HasManyThrough extends Relation
- {
-
- protected $throughKey;
-
- protected $through;
-
- public function __construct(Model $parent, $model, $through, $foreignKey, $throughKey, $localKey)
- {
- $this->parent = $parent;
- $this->model = $model;
- $this->through = $through;
- $this->foreignKey = $foreignKey;
- $this->throughKey = $throughKey;
- $this->localKey = $localKey;
- $this->query = (new $model)->db();
- }
-
- public function getRelation($subRelation = '', $closure = null)
- {
- if ($closure) {
- call_user_func_array($closure, [ & $this->query]);
- }
- return $this->relation($subRelation)->select();
- }
-
- public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
- {
- return $this->parent;
- }
-
- public function hasWhere($where = [], $fields = null)
- {
- throw new Exception('relation not support: hasWhere');
- }
-
- public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
- {}
-
- public function eagerlyResult(&$result, $relation, $subRelation, $closure)
- {}
-
- public function relationCount($result, $closure)
- {}
-
- public function getRelationCountQuery($closure, &$name = null)
- {
- throw new Exception('relation not support: withCount');
- }
-
- protected function baseQuery()
- {
- if (empty($this->baseQuery) && $this->parent->getData()) {
- $through = $this->through;
- $alias = Loader::parseName(basename(str_replace('\\', '/', $this->model)));
- $throughTable = $through::getTable();
- $pk = (new $through)->getPk();
- $throughKey = $this->throughKey;
- $modelTable = $this->parent->getTable();
- $this->query->field($alias . '.*')->alias($alias)
- ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey)
- ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey)
- ->where($throughTable . '.' . $this->foreignKey, $this->parent->{$this->localKey});
- $this->baseQuery = true;
- }
- }
- }
|