2016-12-20 4 views
0

Ich habe unten Code:Laravel 5 viele zu viele Beziehung

$my_array = array(1,2,3); 
$application->computerSkills()->sync($my_array); 

jetzt, wenn ich dd($application->computerSkills) verwenden sie Daten zurück, aber wenn ich über Code der folgenden ändern, gibt es leer.

$current_skills = $application->computerSkills; 

$my_array = array(1,2,3); 
$application->computerSkills()->sync($my_array); 

Dann ist das Ergebnis dd($application->computerSkills) leer. Also warum und wie zu lösen?

Hinweis: mit detach() und attach() hat auch das gleiche Problem.

Hinweis: es ist nur in einer Situation, dass diese Anwendung noch keinen Computer Geschick hat, und es ist das erste Mal.

Hinweis: aber Tabelle einfügen in.

Bellow-Code ist die Beziehung Schiff Funktionen:

/** 
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
*/ 
public function applications(){ 
    return $this->belongsToMany('App\Models\Applications\Application'); 
} 

public function computerSkills(){ 
    return $this->belongsToMany('App\Models\Applications\ComputerSkill'); 
} 

und Tabellenstruktur: applications

id

computer_skills

id

application_computer_skill

APPLICATION_ID

computer_skill_id
+0

was '$ current_skills' tun Hier? –

+0

@AhmadMobaraki Ich brauche es für die Verwendung im Protokoll seiner vorherigen Daten. – jones

+0

Ich nehme an, Ihre 'computerSkill'-Tabelle enthält keine Datensätze mit IDs in' $ my_array'. Wenn Sie also 'sync()' verwenden, werden vorherige Datensätze entfernt und nichts hinzugefügt! –

Antwort

0

Versuchen Sie Ihr Modell Beziehungen als Aktualisierung:

public function applications(){ 
    return $this->belongsToMany('App\Models\Applications\Application', 'application_computer_skill', 'application_id', 'computer_skill_id'); 
} 

public function computerSkills(){ 
    return $this->belongsToMany('App\Models\Applications\ComputerSkill', 'application_computer_skill', 'computer_skill_id', 'application_id'); 
} 

und dann verwenden Sie den Code:

$my_array = array(1,2,3); 
$application->computerSkills()->sync($my_array);