新增模型自动关联功能

This commit is contained in:
JaguarJack 2021-05-31 08:43:29 +08:00
parent 9873a2156b
commit 44f5bf345b
2 changed files with 96 additions and 1 deletions

View File

@ -6,6 +6,7 @@ namespace catcher\base;
use catcher\CatchQuery;
use catcher\traits\db\BaseOptionsTrait;
use catcher\traits\db\RewriteTrait;
use catcher\traits\db\WithTrait;
use think\model\concern\SoftDelete;
use catcher\traits\db\ScopeTrait;
@ -17,7 +18,7 @@ use catcher\traits\db\ScopeTrait;
*/
abstract class CatchModel extends \think\Model
{
use SoftDelete, BaseOptionsTrait, ScopeTrait, RewriteTrait;
use SoftDelete, BaseOptionsTrait, ScopeTrait, RewriteTrait, WithTrait;
protected $createTime = 'created_at';
@ -47,4 +48,14 @@ abstract class CatchModel extends \think\Model
{
return property_exists($this, 'field') && in_array($field, $this->field);
}
public function __construct(array $data = [])
{
parent::__construct($data);
if (method_exists($this, 'autoWithRelation')) {
$this->autoWithRelation();
}
}
}

View File

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* @filename ScopeTrait.php
* @createdAt 2020/6/21
* @project https://github.com/yanwenwu/catch-admin
* @document http://doc.catchadmin.com
* @author JaguarJack <njphper@gmail.com>
* @copyright By CatchAdmin
* @license https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt
*/
namespace catcher\traits\db;
trait WithTrait
{
/**
*
* @time 2021年05月28日
* @return mixed
*/
protected function autoWithRelation()
{
if (property_exists($this, 'globalScope')) {
array_push($this->globalScope, 'withRelation');
}
$this->scope('scopeWith');
if (property_exists($this, 'with')) {
return $this->with($this->with);
}
return $this;
}
/**
*
* @time 2021年05月28日
* @param $query
* @return void
*/
public function scopeWithRelation($query)
{
if (property_exists($this, 'with') && !empty($this->with)) {
$query->with($this->with);
}
}
/**
*
* @time 2021年05月28日
* @param string $withRelation
* @return $this
*/
public function withoutRelation(string $withRelation)
{
$withes = $this->getOptions('with');
foreach ($withes as $k => $item) {
if ($item === $withRelation) {
unset($withes[$k]);
break;
}
}
return $this->setOption('with', $withes);
}
/**
*
* @time 2021年05月28日
* @param string $withRelation
* @return $this
*/
public function withOnlyRelation(string $withRelation)
{
return $this->with($withRelation);
}
}