2016-06-16 19 views
1

Ich benutze Laravel 5.2 und mache eine Website, die Standorte in verschiedenen Kategorien benötigt. Ich möchte den Modellnamen in der Datenbank speichern und mit dem aus der Datenbank abgerufenen Wert abrufen.Speichern von Modellnamen in der Datenbank und Abrufen der Daten

Ich habe ein Hotel Modell

-id 
-name 

Und ich habe Restaurant Modell

-id 
-name 

Und ich habe Lokationsmodell

-id 
-name 
-latitude 
-longitude 
-modal_name 

I App\Hotel in modal_name Spalte speichern wollen und um Daten vom selben Modell zu holen.

Wie gehe ich vor, um dieses Problem zu lösen?

+2

die polymorphen [Beziehungen] prüfen (https://laravel.com/docs/5.2/eloquent-relationships#polymorphic-relations). – Burak

Antwort

0

Der einzige Weg, den ich kenne, ist die polymorphe Beziehung.

Sie sollten Ihre Standorte Tabelle 2 Felder (auf diesem Modell 1 für die Modellnamen und 1 für die ID-Taste) hinzufügen und die Namenskonvention ist in der Regel **** able_type und *** able_id zum Beispiel: locationable_type und locationable_id.

als von Ihrem Standort Modell fügen Sie die folgende Beziehung

class Location extends Model 
{ 
    /** 
    * Get all of the owning locationable models. 
    */ 
    public function locationable() 
    { 
     return $this->morphTo(); 
    } 
} 

als bei Ihrem Hotel Modell hinzufügen, um dieses Verhältnis

class Hotel extends Model 
{ 
    /** 
    * Get the hotel location. 
    */ 
    public function location() 
    { 
     return $this->morphMany('App\Location', 'locationable'); 
    } 
} 

gleiche Sache für Ihr Restaurant Modell

class Restaurant extends Model 
{ 
    /** 
    * Get the restaurant location. 
    */ 
    public function location() 
    { 
     return $this->morphMany('App\Location', 'locationable'); 
    } 
} 

als zu Verwenden Sie es einfach verwenden können:

$hotel = App\Hotel::find(1); 

dd($hotel->location); 

für weitere Informationen können Sie laravel documentation Kasse

Viel Glück :)

Verwandte Themen