用多对多关联的时候,因为执行baseQuery之后就会锁定id,导致relation只有第一个成功. 两个解决思路
- 其它关联方式,嵌套关联
- 自己构建belongsToMany类,覆盖model的belongsToMany方法
Relation.php
public function __call($method, $args)
{
if ($this->query) {
// 执行基础查询
$this->baseQuery();
$result = call_user_func_array([$this->query->getModel(), $method], $args);
return $result === $this->query && !in_array(strtolower($method), ['fetchsql', 'fetchpdo']) ? $this : $result;
} else {
throw new Exception('method not exists:' . __CLASS__ . '->' . $method);
}
}
BelongsToMany.php
/**
* 执行基础查询(仅执行一次)
* @access protected
* @return void
*/
protected function baseQuery()
{
if (empty($this->baseQuery) && $this->parent->getData()) {
$pk = $this->parent->getPk();
$table = $this->pivot->getTable();
$this->query
->join([$table => 'pivot'], 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())
->where('pivot.' . $this->localKey, $this->parent->$pk);
$this->baseQuery = true;
}
}
来源:oschina
链接:https://my.oschina.net/u/2003520/blog/3274263