mirror of
https://gitee.com/fastadminnet/framework.git
synced 2026-07-07 23:22:48 +08:00
belongsToMany增加数据同步方法
This commit is contained in:
@@ -121,7 +121,7 @@ class BelongsToMany extends Relation
|
|||||||
public function getRelation($subRelation = '', $closure = null)
|
public function getRelation($subRelation = '', $closure = null)
|
||||||
{
|
{
|
||||||
if ($closure) {
|
if ($closure) {
|
||||||
call_user_func_array($closure, [ & $this->query]);
|
call_user_func_array($closure, [& $this->query]);
|
||||||
}
|
}
|
||||||
$result = $this->buildQuery()->relation($subRelation)->select();
|
$result = $this->buildQuery()->relation($subRelation)->select();
|
||||||
$this->hydratePivot($result);
|
$this->hydratePivot($result);
|
||||||
@@ -503,6 +503,55 @@ class BelongsToMany extends Relation
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据同步
|
||||||
|
* @param array $ids
|
||||||
|
* @param bool $detaching
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function sync($ids, $detaching = true)
|
||||||
|
{
|
||||||
|
$changes = [
|
||||||
|
'attached' => [],
|
||||||
|
'detached' => [],
|
||||||
|
'updated' => []
|
||||||
|
];
|
||||||
|
$pk = $this->parent->getPk();
|
||||||
|
$current = $this->pivot->where($this->localKey, $this->parent->$pk)
|
||||||
|
->column($this->foreignKey);
|
||||||
|
$records = [];
|
||||||
|
|
||||||
|
foreach ($ids as $key => $value) {
|
||||||
|
if (!is_array($value)) {
|
||||||
|
$records[$value] = [];
|
||||||
|
} else {
|
||||||
|
$records[$key] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$detach = array_diff($current, array_keys($records));
|
||||||
|
|
||||||
|
if ($detaching && count($detach) > 0) {
|
||||||
|
$this->detach($detach);
|
||||||
|
|
||||||
|
$changes['detached'] = $detach;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($records as $id => $attributes) {
|
||||||
|
if (!in_array($id, $current)) {
|
||||||
|
$this->attach($id, $attributes);
|
||||||
|
$changes['attached'][] = $id;
|
||||||
|
} elseif (count($attributes) > 0 &&
|
||||||
|
$this->attach($id, $attributes)
|
||||||
|
) {
|
||||||
|
$changes['updated'][] = $id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $changes;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行基础查询(进执行一次)
|
* 执行基础查询(进执行一次)
|
||||||
* @access protected
|
* @access protected
|
||||||
|
|||||||
Reference in New Issue
Block a user