laravel搜索许多对许多Relashionship
题
我正在第一次测试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
类Eav扩展雄辩{
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()”方法应该为您提供一个唯一的eav与符合您的标准的产品。
$produits = Produit::with( array('eavs' => function($query)
{
$query->where('id', '3')->where('value_int', '3');
}))->has('eavs')->get();
. 不隶属于 StackOverflow