2017-02-10 60 views
1

我建立一個博客應用程序,我有有多個型號

PostCityNeighbourhoodSubNeighbourhood Laravel關係。

,我直到現在的關係之間CityNeighbourhoodsubNeighbourhood喜歡如下:

subNeighbourhood belongs to Neighbourhood 
Neighbourhood belongs to city 

第二個關係是像

City hasMany Neighbourhoods 
Neighbourhood hasMany subNeighbourhoods 

當我創建的帖子我的問題。帖子表格有id_city,id_neighbourhoodid_subNeighbourhood

我有的問題是:

如果帖子結構是正確的?我覺得有很多「ID _...」不好。

第二個問題是我如何在帖子中寫關係?所有列「id _...」都有外鍵到每個對應的表。

+0

在口頭禪中的正常約定是'* _id'符號而不是'id_ *' –

+0

你能給我一個鏈接到這個例子嗎?謝謝 –

+0

https://laravel.com/docs/5.4/eloquent-relationships。如果你願意,你也可以改變關係的列名,你可以自由地這樣做。你想從你的什麼樣的關係將模型發佈到其他模型? –

回答

0

爲了什麼我可以從你的解釋理解後的表應該只有一個subneighbourhood_id場,在Post類的關係應該是:

public function subneighbourhood() 
{ 
    return $this->belongsTo('App\Subneighbourhood'); 

因此,一個專屬於那個屬於附近一個Subneighbourhood屬於一個城市

+0

我理解你的邏輯,但如果我想要得到一個職位的城市,我應該寫$ post-> subneighbourhood-> neighborhood> city,對嗎?並且在這篇文章的保存中,我如何在城市之前編寫洞關係?我對這些複雜的事物很陌生,所以對我來說不清楚。謝謝 –

+0

從你寫的關係很清楚,這是你寫的:$ post-> subneighbourhood-> neighborhood> city。如果你在帖子表中寫了另一個city_id字段,你可以有$ post-> city,但這兩個城市可能不同,我無法想象這是一個場景。 – dparoli

+0

你能給我更多關於這個場景的細節嗎?這部分我不明白,爲什麼這兩個城市有這種可能性是不同的? –

0

我認爲多態關係將是一個很好的解決您的問題。 (我沒測試我的代碼或什麼那麼)

class Post extends Model 
{ 
    // Can return a City or Neighbourhood or SubNeighbourhood 
    public function related() { 
     return $this->morphTo(); 
    } 
} 

class City extends Model 
{ 
    public function posts() { 
     return $this->morphMany(App\Models\Post::class, 'related'); 
    } 
} 


class Neighbourhood extends Model 
{ 
    public function posts() { 
     return $this->morphMany(App\Models\Post::class, 'related'); 
    } 
} 

如何使用:

例如,如果我們具有的選擇關係到一個城市

$post = Post::find(1); 
$true = ($post->related instanceof City); // This will be true if post related to a city 
$neightbourhoods = $post->related->neightbourhoods(); // All the neightbourhoods of the city 

實例後,如果我們具有的選擇與鄰近的後

$post = Post::find(2); 
$true = ($post->related instanceof Neighbourhood); // This will be true if post is related to a neighbourhood 
//In this case we can do 
$post->neighbourhood->subNeighbourhoods(); // All the sub neighbourhoods 

您可以安全方便地後用

$post = new Post(); 
$post->related = City::find(1); 
$post->save(); 

or 

$post = new Post(); 
$post->related = Neighbourhood::find(1); 
$post->save(); 
+0

我已經在我的代碼中創建瞭解決方案,但是當我將在帖子的所有細節(標題,內容等)中保存時,我無法保存。變形不像belongsTo一樣,對吧? (我的意思是自動將city id添加到city_id) –

+0

morph變得更智能一些,並考慮將哪個模型附加到它。它始終在'related_id'上設置模型的id,並確定要在'related_type'字段中查詢關係的表。所以如果'related_type'是「城市」,城市表格將被查詢。如果類型是「鄰居」,則查詢鄰居表。 –

+0

不知道btw爲什麼你不能保存帖子。 –