【问题标题】:Is there a way to use fake class (without database table/model) for polymorphic relationship?有没有办法使用假类(没有数据库表/模型)进行多态关系?
【发布时间】:2021-07-03 20:38:12
【问题描述】:

我有一个transactions 表,其中的事务类型可变形为TopUpTransactionDeductTransaction 等,其中包含其特定信息(因为它们具有不同的字段)。

现在我有一个事务类型SecurityDeposit,它不需要专用模型,因为它不需要任何额外信息。

我可以通过拥有一个模型和一个只保留id 字段的数据库表使其与默认变形一起使用,但这是没有意义的。

有没有办法绕过创建一个空模型和数据库表?

class Transaction extends Model {

    public function transactionable(): MorphTo
    {
        return $this->morphTo();
    }

    public function text() 
    {
        return $this->transactionable->text()
    }

    public function class() 
    {
        return $this->transactionable->class()
    }
}
class TopUpTransaction extends Model {

    public function text() {
        return "Top Up"
    }

    public function class() {
        return "text-success"
    }
}

class DeductTransaction extends Model {
 // has text() and class() methods 
}

但是,我不想在数据库中创建 SecurityDepositTransaction,因为它不需要任何其他信息

class SecurityDepositTransaction { 
    
    public function text() {
        return "Security Deposit"
    }

    public function class() {
        return "text-danger"
    }
}

【问题讨论】:

  • 创建一个扩展 Transation 的经典变形类(不是一个雄辩的变形关系)。您将不得不设置一些属性,例如 $table 等,可能会使其他关系过载。对于关系,您可以只返回一个带有 intanciated Transaction 类属性的新 SecurityDeposit 实例
  • @N69S 你所说的变形类是什么意思?你能在答案部分写下你的方法吗?

标签: laravel eloquent polymorphism laravel-relations


【解决方案1】:

SecurityDeposit 和 Transaction 之间的经典多态关系

class SecurityDeposit extends Transaction
{
    protected $table = 'transactions';
    
    // and use it as if you use Transaction, but it will be a seperate class
    // if for example, this class has a special relation that Transaction doesnt have,
    // you declare it here. same for any speccific method to this class

    public function specialRelation() {
        return $this->hasMany(AnotherClass::class);
    }

    public function getDepositAmounr() {
        return $this->custom_data;
    }
}

【讨论】:

  • 我认为这种方法不适用于 $user->transaction->transactionable 模型和非模型。我错过了什么吗?
  • 它不会像一个雄辩的多态一样工作。为此,您需要使用雄辩的多态。
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
相关资源
最近更新 更多