我有3個表,一個news
錶店的消息,songs
錶店的歌曲,comments
錶店的意見,新聞可以有很多評論,有首歌也可以有很多意見,我comments
表,我使用item_id
,item_type
來確定此評論屬於哪個父模型。例如,如果item_type='game' and item_id=1
比此評論屬於game
表和遊戲ID = 1。 以下是我的型號代碼。雄辯屬於關聯確定關係表
歌曲
class Song
{
public function comment()
{
return $this->hasMany(Comment::class, 'item_id', 'id')->where('comments.item_type', '=', Comment::SONG_COMMENT_TYPE);
}
}
新聞
class News
{
public function comment()
{
return $this->hasMany(Comment::class, 'item_id', 'id')->where('comments.item_type', '=', Comment::NEWS_COMMENT_TYPE);
}
}
評論
class Comment
{
public function song()
{
return $this->belongsTo(Song::class, 'item_id', 'id');
}
public function news()
{
return $this->belongsTo(News::class, 'item_id', 'id');
}
}
可以很容易地從Song
或News
模型得到的意見,但我不知道如何定義反轉關係,是否可以在中定義方法210型號,如:
public function item()
{
if ($this->item_type == Comment::SONG_COMMENT_TYPE) {
return $this->song();
} else {
return $this->news();
}
}
或者,也許我在錯誤的方式在想,如何用雄辯來確定加入上運行時其表?
它看起來像Laravel具有多晶的關係沒有反向(糾正我,如果我錯了)。我認爲這個解決方案對你想達到的目標很有幫助。 –
@ThomasVanderVeen我還在數據庫設計階段爲我的應用程序,你有我的問題的任何建議? – xcaptain
據我所知,您需要在'Comment'模型中爲每個關係定義一個方法。 – haakym