2017-09-25 3 views
0

Ich habe zwei Tabellen survey und question in einem Laravel-Projekt. Ich möchte eine eloquente hasManyThrough-Beziehung erstellen, damit ich alle Fragen, die zur Umfrage gehören, durchlaufen kann.Laravel hasManyThrough - nicht alle erwarteten Ergebnisse

Erhebung Tabelle:

---------------- 
| id | title | 
---------------- 
| 1 | fruit | 
---------------- 

Frage Tabelle:

---------------- 
| id | title | 
---------------- 
| 1 | apple? | 
| 3 | banana? | 
| 4 | kiwi? | 
| 5 | pear? | 
---------------- 

SurveyQuestion Tabelle:

-------------------------------- 
| id | survey_id | question_id | 
-------------------------------- 
| 1 | 1   | 1   | 
| 1 | 1   | 4   | 
| 1 | 1   | 5   | 
-------------------------------- 

In meiner Umfrage Modell Im Moment habe ich die folgende

public function questions() 
{ 
    return $this->hasManyThrough(
     Questions::class, 
     SurveyQuestion::class, 
     'question_id', // Foreign key on surveyquestion table... 
     'id', // Foreign key on questions table... 
     'id', // Local key on survey table... 
     'survey_id' // Local key on surveyquestion table... 
    ); 
} 

und in meinem SurveyQuestion Modell ich habe:

public function survey() 
{ 
    return $this->belongsTo(Survey::class); 
} 

public function question() 
{ 
    return $this->belongsTo(Questions::class); 
} 

Jedoch, wenn ich Schleife durch $survey->questions es nur kehrt die Zeile, wenn question_id 1? Was habe ich falsch gemacht?

+1

Ihre Umfrage und Fragetabelle enthalten keine Beziehung. Überprüfen Sie, dass: https://laravel.com/docs/5.5/eloquent-relationships#has-many-through –

+0

@MahfuzShishir Dank der Verwendung von vielen zu vielen Beziehung vorgeschlagen von Morteza gelöst mein Problem. – xylar

Antwort

1

Es ist eine viel zu viele Beziehung.

Umfrage Modell

public function questions() 
{ 
    return $this->belongsToMany(Question::class, 'survey_question'); 
} 

Frage Modell

public function surveys() 
{ 
    return $this->belongsToMany(Survey::class, 'survey_question'); 
} 

Dann können Sie

$survey = Survey::with('questions')->find($id); 

@foreach($survey->questions as $question) 
    //... 
@endforeach 
+0

@xylar vergessen Sie nicht zu wählen. –

0

Siehe die docs

für 01 der Struktur NachSie brauchen Struktur haben wie diese

Umfrage id - integer Name - String

Frage id - integer survey_id - integer Name - String

SurveyQuestion id - ganze Zahl question_id - integer Titel - String

Aber Sie haben nicht Fremdschlüssel in der Zwischentabelle dieser ersten fixieren und dann werde ich denke, Sie dieses Problem loszuwerden.

Verwandte Themen