改进HasMany和OneToOne

This commit is contained in:
thinkphp
2017-01-17 10:53:14 +08:00
parent ebfcbac863
commit ed3becf64f
3 changed files with 21 additions and 8 deletions

View File

@@ -245,7 +245,7 @@ class HasMany extends Relation
} }
return $this->parent->db()->alias($model) return $this->parent->db()->alias($model)
->field($model . '.*') ->field($model . '.*')
->join($table . ' ' . $relation, $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $this->joinType) ->join($table . ' ' . $relation, $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey)
->where($where); ->where($where);
} }

View File

@@ -54,24 +54,25 @@ class HasOne extends OneToOne
/** /**
* 根据关联条件查询当前模型 * 根据关联条件查询当前模型
* @access public * @access public
* @param Model $model 模型对象
* @param mixed $where 查询条件(数组或者闭包) * @param mixed $where 查询条件(数组或者闭包)
* @return Query * @return Query
*/ */
public function hasWhere($model, $where = []) public function hasWhere($where = [])
{ {
$table = $this->query->getTable(); $table = $this->query->getTable();
$model = basename(str_replace('\\', '/', get_class($this->parent)));
$relation = basename(str_replace('\\', '/', $this->model));
if (is_array($where)) { if (is_array($where)) {
foreach ($where as $key => $val) { foreach ($where as $key => $val) {
if (false === strpos($key, '.')) { if (false === strpos($key, '.')) {
$where['b.' . $key] = $val; $where[$relation . '.' . $key] = $val;
unset($where[$key]); unset($where[$key]);
} }
} }
} }
return $model->db()->alias('a') return $this->parent->db()->alias($model)
->field('a.*') ->field($model . '.*')
->join($table . ' b', 'a.' . $this->localKey . '=b.' . $this->foreignKey, $this->joinType) ->join($table . ' ' . $relation, $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $this->joinType)
->where($where); ->where($where);
} }

View File

@@ -26,6 +26,18 @@ abstract class OneToOne extends Relation
// 要绑定的属性 // 要绑定的属性
protected $bindAttr = []; protected $bindAttr = [];
/**
* 设置join类型
* @access public
* @param string $type JOIN类型
* @return $this
*/
public function joinType($type)
{
$this->joinType = $type;
return $this;
}
/** /**
* 预载入关联查询JOIN方式 * 预载入关联查询JOIN方式
* @access public * @access public