Come definire una relazione polimorfica molti a molti con campi aggiuntivi?Laravel: rapporto polinomico da molti a molti con campi aggiuntivi
Ho tre (o più, come è una relazione polimorfa) tabelle.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
La user_id
sulle referes tabella contrassegnate alla tabella utenti su colonna id. Nel mio modello Post ho:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
e nel mio modello Tag ho:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Poi quando mi trovo provare questo nel mio controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
ottengo Integrità Violazione di vincoli per non avere un id utente:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
hb
.tagged
, CONSTRAINTtagged_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
)) (SQL: insert intotagged
(tag_id
,taggable_id
,taggable_type
) values (26, 2, App\Resource)). Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Inoltre, ho provato withPivot() sul tag relazione come segue, senza alcun risultato:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Hai provato? –
Provato conPivot()? Il problema è che come posso assegnare l'attributo. Ho provato withPivot ('user_id') e ottengo ancora un errore di limitazione dell'integrità quando passo un array che contiene anche user_id al metodo create. Non inserisce user_id nella sua query. – CrackingTheCode
'creating' non ha praticamente nulla a che fare con' withPivot'. Quindi, invece della domanda che hai postato (leggi questo http://xyproblem.info/) mostra cosa stai cercando di fare, cosa ti aspetti e cosa invece ottieni. –