mirror of
https://gitee.com/fastadminnet/framework.git
synced 2026-07-01 12:42:48 +08:00
修正BELONGS_TO关联查询
This commit is contained in:
@@ -729,17 +729,17 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
|
||||
* BELONGS TO 关联定义
|
||||
* @access public
|
||||
* @param string $model 模型名
|
||||
* @param string $localKey 关联主键
|
||||
* @param string $foreignKey 关联外键
|
||||
* @param string $otherKey 关联主键
|
||||
* @return \think\db\Query|string
|
||||
*/
|
||||
public function belongsTo($model, $localKey = '', $foreignKey = '')
|
||||
public function belongsTo($model, $foreignKey = '', $otherKey = '')
|
||||
{
|
||||
// 记录当前关联信息
|
||||
$model = $this->parseModel($model);
|
||||
$foreignKey = $foreignKey ?: $this->pk;
|
||||
$localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id';
|
||||
return $this->relation->belongsTo($model, $foreignKey, $localKey);
|
||||
$foreignKey = $foreignKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id';
|
||||
$otherKey = $otherKey ?: (new $model)->getPk();
|
||||
return $this->relation->belongsTo($model, $foreignKey, $otherKey);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -74,7 +74,6 @@ class Relation
|
||||
// 判断关联类型执行查询
|
||||
switch ($this->type) {
|
||||
case self::HAS_ONE:
|
||||
case self::BELONGS_TO:
|
||||
$result = $relation->where($foreignKey, $this->parent->$localKey)->find();
|
||||
if (false === $result) {
|
||||
$class = $this->model;
|
||||
@@ -82,6 +81,14 @@ class Relation
|
||||
$result->$foreignKey = $this->parent->$localKey;
|
||||
}
|
||||
break;
|
||||
case self::BELONGS_TO:
|
||||
$result = $relation->where($localKey, $this->parent->$foreignKey)->find();
|
||||
if (false === $result) {
|
||||
$class = $this->model;
|
||||
$result = new $class;
|
||||
$result->$localKey = $this->parent->$foreignKey;
|
||||
}
|
||||
break;
|
||||
case self::HAS_MANY:
|
||||
$result = $relation->where($foreignKey, $this->parent->$localKey)->select();
|
||||
break;
|
||||
@@ -368,17 +375,17 @@ class Relation
|
||||
* BELONGS TO 关联定义
|
||||
* @access public
|
||||
* @param string $model 模型名
|
||||
* @param string $localKey 关联主键
|
||||
* @param string $foreignKey 关联外键
|
||||
* @param string $localKey 关联主键
|
||||
* @return \think\db\Query|string
|
||||
*/
|
||||
public function belongsTo($model, $localKey, $foreignKey)
|
||||
public function belongsTo($model, $foreignKey, $otherKey)
|
||||
{
|
||||
// 记录当前关联信息
|
||||
$this->type = self::BELONGS_TO;
|
||||
$this->model = $model;
|
||||
$this->foreignKey = $foreignKey;
|
||||
$this->localKey = $localKey;
|
||||
$this->localKey = $otherKey;
|
||||
|
||||
// 返回关联的模型对象
|
||||
return $this;
|
||||
|
||||
Reference in New Issue
Block a user