Laravel 将子类belongsTo关系设置为特定值

Laravel 将子类belongsTo关系设置为特定值,laravel,laravel-5.4,Laravel,Laravel 5.4,以下是我的模式: Schema::create('agents', function (Blueprint $table) { $table->increments('id'); $table->increments('name'); $table->integer('agent_type_id')->nullable(); $table->foreign('agent_type_id')->references('id')-&

以下是我的模式:

Schema::create('agents', function (Blueprint $table) {
    $table->increments('id');
    $table->increments('name');
    $table->integer('agent_type_id')->nullable();
    $table->foreign('agent_type_id')->references('id')->on('agent_types');
    $table->timestamps();
});

Schema::create('agent_types', function (Blueprint $table) {
    $table->increments('id');
    $table->increments('title');
    $table->timestamps();
});
这是我的
代理
模型:

class Agent extends Model
{

    public function agentType()
    {

        return $this->belongsTo('AgentType');

    }

}
一个特定的
AgentType
记录将具有标题
Artist
。因此,我想创建一个
Artist
模型,该模型扩展了
Agent
,并将其
agentType()
预设为指向该特定记录。我将有几种不同类型的代理,所以我也考虑将其作为其他代理类型的模式来实现

所以有几个问题:

  • 这是好的做法吗?还是我应该远离这个想法
  • 如何在子
    Artist
    类中设置
    agentType()
    方法,以指向该类所有实例的特定记录

我最终使用了Eloquent的方法来定义子类的特定值:

class Artist extends Agent
{

    public function getAgentTypeAttribute()
    {

        AgentType::where('title', 'Artist')->first();

    }

}

超级简单的解决方案

考虑为此利用模型事件,尤其是
创建
。您可以在每个子类中设置title属性,然后在创建类型时查询该类型。它将提供一个通用的解决方案,使您不必在每个模型上都使用访问器方法。