Laravel - 多对多关系约束急切加载
Laravel - manytomany relationship constrain eager load
多对多关系约束
table:产品
Product_id
类别
Table:特点
Feature_id: 11
Feature_name: 远程
枢轴table:FeatureProduct
Feature_id
Product_id
$products = App\Product::with([‘features' => function ($query) {
$query->where(‘id’, 11);
}])->where(‘category_id’, 17)->get();
仍然得到category = 11的所有产品,不过滤掉feature_id = 11
:with Query where子句,我不知道该放什么,是ID所属的特征。
单品输出是这样的
Product {#1372 ▼
#original: array:13 [▼
"id" => 1
"code" => "PL6881"
"v_description" => "E14 41 bóng + LED pha lê 642 hạt"
"width" => 1200
"length" => null
"height" => 1800
"price" => 47800000
"vendor_id" => 1
"category_id" => 17
"active" => 1
"discount" => 0
"hero" => 0
"promote" => 0
]
#relations: array:1 [▼
"features" => Collection {#5858 ▼
#items: array:3 [▼
0 => Feature {#3149 ▼
#attributes: array:4 [▼
"id" => 3
"code" => "Chau Au"
"v_description" => "Châu Âu"
"att_cate_id" => 1
]
}
1 => Feature {#3340 ▶}
2 => Feature {#3492 ▶}
]
}
]
}
试试下面的代码,
$products = App\Product::with([‘features'])
->whereHas(‘features', function ($query) {
$query->where(‘id’, 11);
})->where(‘category_id’, 17)->get();
我已经编辑了答案。请立即查看
我发现这很有用
$products = Product::with('features')->whereHas('features', function ($query) {
return $query->where('id', 3);
})->where('category_id',17)->get();
多对多关系约束
table:产品 Product_id 类别
Table:特点 Feature_id: 11 Feature_name: 远程
枢轴table:FeatureProduct Feature_id Product_id
$products = App\Product::with([‘features' => function ($query) {
$query->where(‘id’, 11);
}])->where(‘category_id’, 17)->get();
仍然得到category = 11的所有产品,不过滤掉feature_id = 11
:with Query where子句,我不知道该放什么,是ID所属的特征。
单品输出是这样的
Product {#1372 ▼
#original: array:13 [▼
"id" => 1
"code" => "PL6881"
"v_description" => "E14 41 bóng + LED pha lê 642 hạt"
"width" => 1200
"length" => null
"height" => 1800
"price" => 47800000
"vendor_id" => 1
"category_id" => 17
"active" => 1
"discount" => 0
"hero" => 0
"promote" => 0
]
#relations: array:1 [▼
"features" => Collection {#5858 ▼
#items: array:3 [▼
0 => Feature {#3149 ▼
#attributes: array:4 [▼
"id" => 3
"code" => "Chau Au"
"v_description" => "Châu Âu"
"att_cate_id" => 1
]
}
1 => Feature {#3340 ▶}
2 => Feature {#3492 ▶}
]
}
]
}
试试下面的代码,
$products = App\Product::with([‘features'])
->whereHas(‘features', function ($query) {
$query->where(‘id’, 11);
})->where(‘category_id’, 17)->get();
我已经编辑了答案。请立即查看
我发现这很有用
$products = Product::with('features')->whereHas('features', function ($query) {
return $query->where('id', 3);
})->where('category_id',17)->get();