Laravel-Eloquent嵌套关系枢轴与约束


Laravel Eloquent nested relation pivot with constraint

我目前正在使用laravel 4我试图在有约束的情况下检索集合,但它不能像预期的那样工作

模型特征:

public function valeur() {
    return $this->hasMany('Valeur','id_caracteristique','id');
}

型号价值

public function caracteristique() {
    return $this->belongsTo('Caracteristique','id','id_caracteristique');
}
public function produit() {
    return $this->belongsToMany('Produit','produit_valeur');
}

型号类别

public function produit() {
    return $this->belongsToMany('Produit','produit_categorie');
}

型号产品

public function valeur() {
    return $this->belongsToMany('Valeur','produit_valeur');
}

我想要:

Caracteristique,其值为categorie=x,通过产品

最终目标:能够像一样解析集合

caracteristique->valeur;

在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

当我在雄辩的关系中使用join时,不再可用

我试过这个:

$carac = Caracteristique::with(array('valeur.produit.categorie' => function($q) {
$q->whereCategorieId(2);
 }))->get();

但约束没有得到尊重。。

有什么想法吗?

问候,

找到这个糟糕的解决方案。。。

$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();

有最佳实践的人?

如果您想要限制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();

或者如果您只想加载所有Caracteristique和限制相关的Valeur

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();

正如您所看到的,这不是最好的代码,所以只需使用联接即可。