Come posso ottenere il post del tag con eloquente orm
Domanda
Ho le tavole basate su ordinazione e tag basate su ormi.Tag assegnati al post su una tabella di pivot.Per ottenere post-> tag a Laravel I uso sotto il modello relation.
//Model: Post
public function tags()
{
$this->belongsToMany('Tag', 'post_tag', 'post_id', 'tag_id');
}
.
Ecco il mio database:
post
id
tags
id
post_tag
post_id
tag_id
.
domanda
Voglio recuperare tutti i post con un nome tag spedito.
Cosa ho provato
Post::with(array('tags' => function($query)
{
$query->where('id', '=', 44);
}))->get();
con caricamento desideroso.Ma ha dato un errore di integrità.
Inoltre ho provato la relazione della query, lanciare errore non oggetto.
Post::whereHas('tags', function($q)
{
$q->where('id', '=', $tag_id);
})->get();
. Soluzione
La relazione è bidirezionale
È necessario definire il tuo tag del modello AS
class Tag{
public function posts()
{
return $this->belongsToMany('Post');
}
}
.
puoi farlo
$posts = Tag::find(44)->posts;
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow