2017-06-17 56 views
0

這裏是我的架構:設置子類屬於關聯關係爲特定值

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(); 
}); 

這裏是我的Agent型號:

class Agent extends Model 
{ 

    public function agentType() 
    { 

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

    } 

} 

一個特別AgentType記錄將有標題Artist。所以我想創建一個Artist模型,它擴展了Agent,並且其agentType()預設爲指向該特定記錄。我將要有幾種不同類型的代理,所以我正在考慮將此作爲其他代理類型的模式。

那麼幾個問題:

  • 這是很好的做法?或者我應該遠離這個想法嗎?
  • 我該如何設置子類ArtistagentType()方法來指向該類的所有實例的特定記錄?

回答

0

最後我用雄辯的Accessor方法來定義的子類特定值:

class Artist extends Agent 
{ 

    public function getAgentTypeAttribute() 
    { 

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

    } 

} 

超級簡單的解決方案!

+1

考慮利用模型事件,特別是'創造'。您可以在每個子類中設置title屬性,然後在創建類型時查詢它的類型。它將提供一個通用的解決方案,並使您無需在每個模型上使用訪問器方法。 https://laravel.com/docs/5.4/eloquent#events – btl