【问题标题】:ATK4 CRUD: Lookup reference table for data insertionATK4 CRUD:用于数据插入的查找参考表
【发布时间】:2020-07-22 10:15:34
【问题描述】:

我有某些类型的元素。 我有某些类型的垃圾箱。 一个元素只属于同一类型的bin。

数据库中的一个表包含元素。 另一个表包含垃圾箱。 它们每个都有一个“type_id”。

就元素而言,有几个模型,除了抽象基础模型之外,每个模型都设置了 ->addCondition('type', '=', 'x')。

现在在实例化 X 类型元素的 CRUD 时,在添加或编辑项目时,如何防止 Y 类型的 bin 显示在下拉列表中?

本质上,我想对 hasOne() 施加一个附加条件,以限制显示的外部值。

class AbstractElement extends \atk4\data\Model {
  public $table = 'element';
  public $id_field = 'element_id';
  public $title_field = 'element_data';

  function init() {
    parent::init();

    $this->hasOne('Bin', [Bin::class, 'our_field'=>'element_bin_id', 'caption'=>'Bin', 'required'=>true])->addTitle(['caption'=>'Bin']);
    $this->addField('element_data', ['required'=>true]);
    $this->hasOne('Type', [Type::class, 'our_field'=>'type_id']);
  }
}
class Element extends AbstractElement {
  function init() {
    parent::init();
    $this->addCondition('type_id', '=', '1');
  }
}

class Bin extends \atk4\data\Model {
  public $table = 'bin';
  public $id_field = 'bin_id';
  public $title_field = 'bin_name';

  function init() {
    parent::init();

    $this->addField('bin_name', ['caption'=>'Name']);
    $this->hasOne('Type', [Type::class, 'our_field'=>'bin_type_id']);
  }
}

class Type extends \atk4\data\Model {
  public $table = 'type';
  public $id_field = 'type_id';
  public $title_field = 'type_name';

  function init() {
    parent::init();

    $this->addField('type_name');
  }
}

【问题讨论】:

    标签: atk4


    【解决方案1】:

    我认为这应该可行。

    Type 类中添加:

    $this->hasMany('Bins', [Bin::class, 'their_field'=>'bin_type_id']);
    

    AbstractElement类中使用回调定义Bin hasOne关系:

    $this->hasOne('Bin', [
        function($m){
            return $m->ref('Type')->ref('Bins');
        },
        'our_field' => 'element_bin_id',
        'caption' => 'Bin',
        'required' => true,
    ])->addTitle(['caption'=>'Bin']);
    

    【讨论】:

    • 哇,确实如此。谢谢你,先生。你愿意用几句话详细说明正在发生的事情吗?我先试试。因此,我们没有将静态引用传递给某个模型,而是给它一个函数,该函数每次都采用当前正在考虑的模型实例,并首先将其链接到其类型(过滤掉其他类型),从而在第二参考?我必须弄清楚这些回调......我有一种感觉,让我无法充分发挥它的潜力。
    • 是的,它的工作原理与您所说的完全一样-每次调用 ref('Bin') 时,它都会调用 calback 方法,而不是静态引用。唯一有点棘手的情况是创建新元素记录时。在为 Element 设置 type_id 之前,不应使用 ref('Bin')。
    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2016-02-24
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多