I am currently working with laravel 4 I am trying to retrieve collection with constraint but it doesn't work as expected
model Caracteristique :
public function valeur() {
return $this->hasMany('Valeur','id_caracteristique','id');
}
model valeur
public function caracteristique() {
return $this->belongsTo('Caracteristique','id','id_caracteristique');
}
public function produit() {
return $this->belongsToMany('Produit','produit_valeur');
}
model categorie
public function produit() {
return $this->belongsToMany('Produit','produit_categorie');
}
model produit
public function valeur() {
return $this->belongsToMany('Valeur','produit_valeur');
}
I want :
Caracteristique, with values where categorie = x through produit
final goal : To be able parsing collection like
caracteristique->valeur;
in SQL
SELECT c.id,v.id FROM caracteristique c
INNER JOIN valeur v on (v.id_caracteristique = c.id)
INNER JOIN produit_valeur pv on (pv.valeur_id = v.id)
INNER JOIN produit_categorie pc on (pc.produit_id = pv.produit_id)
GROUP by c.id
When i use join in eloquent relationship no longer available
I have tried this :
$carac = Caracteristique::with(array('valeur.produit.categorie' => function($q) {
$q->whereCategorieId(2);
}))->get();
But the constraint not respected ..
Any ideas ?
Regards,
find this bad solution ...
$values = Valeur::whereHas('produit',function($q) {
$q->whereHas('categorie',function($q) {
$q->where('categorie.id','=',2);
});
})->lists('id');
$carac = Caracteristique::with(array('valeur' =>function ($q) use($values) {
$q->wherein('id',$values);
}))->get();
Someone with best practice ?
If you want limit Caracteristique
:
$catId = 2;
Caracteristique::whereHas('valeur', function ($q) use ($catId) {
$q->whereHas('produit', function ($q) use ($catId) {
$q->whereHas('categorie', function ($q) use ($catId) {
$q->where('cateogorie.id', $catId);
});
});
})->get();
or if you want to load all Caracteristique
and limit related Valeur
only:
Caracteristique::with(['valeur' => function ($q) use ($catId) {
$q->whereHas('produit', function ($q) use ($catId) {
$q->whereHas('categorie', function ($q) use ($catId) {
$q->where('cateogorie.id', $catId);
});
});
}])->get();
As you can see this is not the best piece of code to use, so instead simply use joins.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.