多对多关联如何使用条件查询
来源:8-2 模型关联----定于关联与查询关联
XING13
2020-10-14
有三张表:product、theme、product_theme,多对多关联有没有类似haswhere的方法?该如何通过theme表的条件进行查询,并根据theme表的name排序?比如说我要查询商品名称包含“红色”,并且商品标签“衣服”的商品。
//在product模型中使用多对多关联theme
public function themes()
{
return $this->belongsToMany('Theme', 'product_theme', 'te_id', 'pt_id');
}
// 查询---我这样查出来的数据并不对,应该如何查询?
ProductModel::with([
'themes' => function ($query) {
$query->alias('te')
->hidden(['pivot', 'create_time', 'update_time', 'delete_time'])
->where('name','=','衣服');
}, 'materials'])
->where('name','like','红色')->select();写回答
1回答
-
这个应该是可以用子查询的,但是可能写起来会非常麻烦。
建议
先查询到内存中 做过滤
直接写原生SQL查询
122020-10-15
相似问题