改进关联模型的关联键值和表名读取

This commit is contained in:
thinkphp
2016-04-20 15:31:25 +08:00
parent b3d592da95
commit 02934b0d27
3 changed files with 8 additions and 6 deletions

View File

@@ -862,9 +862,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
{
// 记录当前关联信息
$model = $this->parseModel($model);
$table = $table ?: Db::name(strtolower($this->name . '_' . basename(str_replace('\\', '/', $model))))->getTableName();
$localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id';
$foreignKey = $foreignKey ?: strtolower($this->name) . '_id';
$name = Loader::parseName(basename(str_replace('\\', '/', $model)));
$table = $table ?: Db::name(Loader::parseName($this->name) . '_' . $name)->getTableName();
$localKey = $localKey ?: $name . '_id';
$foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id';
return $this->relation->belongsToMany($model, $table, $localKey, $foreignKey);
}

View File

@@ -845,13 +845,13 @@ class Query
$info = $class->getRelationInfo();
if (in_array($info['type'], [Relation::HAS_ONE, Relation::BELONGS_TO])) {
if (0 == $i) {
$joinName = strtolower(basename(str_replace('\\', '/', $this->options['model'])));
$joinName = Loader::parseName(basename(str_replace('\\', '/', $this->options['model'])));
$joinTable = $this->connection->getTableName();
$this->table($joinTable)->alias($joinName)->field(true, false, $joinTable, $joinName);
}
// 预载入封装
$table = $info['model']::getTableName();
$name = strtolower(basename(str_replace('\\', '/', $info['model'])));
$name = Loader::parseName(basename(str_replace('\\', '/', $info['model'])));
$this->via($name);
$this->join($table . ' ' . $name, $joinName . '.' . $info['localKey'] . '=' . $name . '.' . $info['foreignKey'])->field(true, false, $table, $name, $name . '__');
if ($closure) {

View File

@@ -13,6 +13,7 @@ namespace think\model;
use think\Db;
use think\Exception;
use think\Loader;
use think\model\Pivot;
class Relation
@@ -257,7 +258,7 @@ class Relation
*/
protected function match($model, $relation, &$result)
{
$modelName = strtolower(basename(str_replace('\\', '/', $model)));
$modelName = Loader::parseName(basename(str_replace('\\', '/', $model)));
// 重新组装模型数据
foreach ($result->toArray() as $key => $val) {
if (strpos($key, '__')) {