在 Laravel 中扩展 Eloquent 模型(使用不同的表) [英] Extending Eloquent Models in Laravel (use different tables)

查看:14
本文介绍了在 Laravel 中扩展 Eloquent 模型(使用不同的表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个涉及跟踪不同类型潜在客户的 Laravel 应用程序.例如,有再融资线索采购线索.

I’m building a Laravel application that involves tracking different types of leads. For example, there are Refinance leads and Purchase leads.

由于leads共享了很多信息和功能,但不是全部,我的想法是创建一个Lead类,它扩展了Laravel的Model类,然后是一个RefinanceLead 类,它扩展了 Lead 类.

Since the leads share a lot of information and functionality, but not all, my thinking was to create a Lead class, which extends Laravel’s Model class, and then a RefinanceLead class, which extends the Lead class.

所以我有:

class Lead extends Model
{
    // shared lead stuff
}

class RefinanceLead extends Lead
{
    // stuff specific to refinance leads
}

我的问题是:

  1. 这个策略有意义吗?
  2. 如果是这样,Eloquent 将如何处理数据?我会有 leads 表和 refinance_leads 表吗?
  3. RefinanceLead 类的新实例是否会使用 leads 表中的任何内容?
  1. Does this strategy make sense?
  2. If it does, how is Eloquent going to handle the data? Will I have a leads table and a refinance_leads table?
  3. Will a new instance of the RefinanceLead class utilize anything in the leads table?

我无法通过文档回答这个问题,但如果我错过了解释的地方,请告诉我.谢谢.

I’ve had trouble answering this question via the documentation, but if I missed where this is explained, please let me know. Thanks.

推荐答案

1. 是的,在父模型中拥有所有通用功能是非常有意义的.

1. Yes, it makes perfect sense to have all the common functionality in a parent model.

2. 基本上,每个 Eloquent 模型都将处理在 protected $table 变量中定义的自己的表中的数据.您可以覆盖父变量为所有不同的子模型设置单独的表.Laravel 表名

2. Basically each Eloquent model will handle the data from its own table defined in the protected $table variable. You can override the parent variable to set a separate table for all the different child models. Laravel Table Names

例如,如果您在 RefinanceLead 实例上使用 getId() 方法,它将从 refinance_lead 返回 idem> 表.如果您在 PurchadeLead 实例上使用它,它将从 purchade_table

For example if you use the getId() method on a RefinanceLead instance it will return the id from refinance_lead table. If you use it on a PurchadeLead instance it will retirn the id from purchade_table

class Lead extends Model
{
    public function getId() {
       return $this->id;
    }
}

class RefinanceLead extends Lead
{
     protected $table = 'refinance_leads';
}

class PurchaseLead extends Lead
{
    protected $table = 'purchase_leads';
}

3. 我不知道您的确切需求是什么,但总的来说,我建议将 Lead 类设为抽象类,这样您就不必为它关联表.仅将其用于分离通用功能、关系等...当然,正如评论中所建议的,实现接口总是一个好主意.

3. I don't know what are your exact needs, but in general I'll suggest making the Lead class abstract and so you don't associate a table for it. Use it only to separate common functionality, relations, etc... Of course as it was suggested in the comments, implementing an interface is always a good idea.

abstract class Lead extends Model implements LeadContract
{
   // class body
}

这篇关于在 Laravel 中扩展 Eloquent 模型(使用不同的表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆