質問
初めて eloquent をテストしているのですが、それが自分のアプリケーションに合うかどうかを確認したいと思っています。
製品テーブルがあります:
id, name
そしてモデル:
class Produit extends Eloquent {
public function eavs()
{
return $this->belongsToMany('Eav')
->withPivot('value_int', 'value_varchar', 'value_date');
}
}
そして eav テーブル:
id, name, code, field_type
そしてピボットテーブル:
product_id, eav_id, value_int, value_varchar, value_date
class Eav extends Eloquent {
public function produitTypes()
{
return $this->belongsToMany(
'ProduitType'
->withPivot('cs_attributs_produits_types_required');
}
これはすべて機能しています。しかし、私はその関係性を探りたいのです。例えば:eav_id=3 および value_int=3 を持つすべての製品
私はこれをテストしました:
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
}))->get();
ただし、すべての製品と、id = 3 および value_int = 3 を持つこれらの eav データのみを取得します。
この検索に一致する商品のみを取得したいのですが...ありがとう
解決
私の提案、そして私が従うべきことは、 知っていることから始める. 。この場合、私たちが知っているのは、 eav_id
, それでは、そこから行きましょう。
$produits = Eav::find(3)->produits()->where('value_int', '3')->get();
この場合、熱心にロードしてもパフォーマンスは向上しません。ドキュメントで説明されているように 1+n クエリの問題を削減しているためです。 find()
. 。また、読みやすく、理解しやすくなります。
クエリビルダーを使用して複数の eav をチェックする
$produits = DB::table('produits')
->join('eav_produit', 'eav_produit.produit_id', '=', 'produits.id')
->join('eavs', 'eavs.id', '=', 'eav_produit.eav_id')
->where(function($query)
{
$query->where('eav_produit.value_int','=','3');
$query->where('eavs.id', '=', '3');
})
->orWhere(function($query)
{
$query->where('eav_produit.value_int','=','1');
$query->where('eavs.id', '=', '1');
})
->select('produits.*')
->get();
すでに持っているものを使って機能させる...
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
$query->orWhere('id', '1')->where('value_int', '1');
}))->get();
foreach($produits as $produit)
{
if(!produit->eavs)
continue;
// Do stuff
}
他のヒント
http://four.laravel.com/docs/eloquent :
When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, you wish to pull all blog posts that have at least one comment. To do so, you may use the has method
$posts = Post::has('comments')->get();
.
"has()"メソッドを使用すると、あなたの基準に一致する軒のみがある製品のみを提供するべきです。
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
}))->has('eavs')->get();
. 所属していません StackOverflow