多对多关联设置中间表模型

增加wherePivot方法
This commit is contained in:
yunwuxin
2017-03-02 14:15:00 +08:00
parent 7a7ebee5c1
commit 6d2541585d

View File

@@ -20,9 +20,12 @@ use think\model\Relation;
class BelongsToMany extends Relation
{
// 中间表模型
// 中间表表名
protected $middle;
// 中间表模型
protected $pivot;
/**
* 构造函数
* @access public
@@ -42,6 +45,28 @@ class BelongsToMany extends Relation
$this->query = (new $model)->db();
}
/**
* 设置中间表模型
* @param $pivot
* @return $this
*/
public function pivot($pivot)
{
$this->pivot = $pivot;
return $this;
}
/**
* 实例化中间表模型
* @param $data
* @return mixed
*/
protected function newPivot($data)
{
$pivot = $this->pivot ?: '\\think\\model\\Pivot';
return new $pivot($data, $this->middle);
}
/**
* 延迟获取关联数据
* @param string $subRelation 子关联名
@@ -54,7 +79,7 @@ class BelongsToMany extends Relation
$localKey = $this->localKey;
$middle = $this->middle;
if ($closure) {
call_user_func_array($closure, [ & $this->query]);
call_user_func_array($closure, [& $this->query]);
}
// 关联查询
$pk = $this->parent->getPk();
@@ -71,7 +96,7 @@ class BelongsToMany extends Relation
}
}
}
$set->pivot = new Pivot($pivot, $this->middle);
$set->pivot = $this->newPivot($pivot);
}
return $result;
}
@@ -95,12 +120,27 @@ class BelongsToMany extends Relation
* @access public
* @param mixed $where 查询条件(数组或者闭包)
* @return Query
* @throws Exception
*/
public function hasWhere($where = [])
{
throw new Exception('relation not support: hasWhere');
}
/**
* 设置中间表的查询条件
* @param $field
* @param null $op
* @param null $condition
* @return $this
*/
public function wherePivot($field, $op = null, $condition = null)
{
$field = 'pivot.' . $field;
$this->query->where($field, $op, $condition);
return $this;
}
/**
* 预载入关联查询(数据集)
* @access public
@@ -230,7 +270,7 @@ class BelongsToMany extends Relation
}
}
}
$set->pivot = new Pivot($pivot, $this->middle);
$set->pivot = $this->newPivot($pivot);
$data[$pivot[$this->localKey]][] = $set;
}
return $data;
@@ -327,7 +367,7 @@ class BelongsToMany extends Relation
foreach ($ids as $id) {
$pivot[$this->foreignKey] = $id;
$this->query->table($this->middle)->insert($pivot, true);
$result[] = new Pivot($pivot, $this->middle);
$result[] = $this->newPivot($pivot);
}
if (count($result) == 1) {
// 返回中间表模型对象