Laravel中有什么方法可以严格whereHas方法吗?
Is there any eay to strict whereHas method in Laravel?
whereHas
Laravel 中的方法使用 MySQL 中的 EXISTS
。问题是,例如,当指定品牌和文本时,它会在文本存在的地方获取所有有或没有品牌的项目……但我需要,当指定品牌时,它只需要那些有品牌和文本的项目。
$parts = AutoPart\Part::has('classifier')->with(['details', 'classifier', 'order', 'place'])-> orderBy('id', 'desc');
if ($brand = $request->get('brand', FALSE)) {
$parts->whereHas('details', function($query) use($brand) {
$query->where('brand', '=', $brand);
});
}
if ($model = $request->get('model', FALSE)) {
$parts->whereHas('details', function($query) use($model) {
$query->where('model', '=', $model);
});
}
if ($text = $request->get('text', FALSE)) {
if (strlen($text) > 0) {
$parts->whereHas('details', function($query) use($text) {
$query->where('notes', 'LIKE', '%' . $text . '%');
});
$parts->orWhereHas('classifier', function($query) use($text) {
$query->where('name', 'LIKE', '%' . $text . '%');
});
}
}
将最后一个条件更改为
if ($text = $request->get('text', FALSE)) {
if (strlen($text) > 0) {
// This will put a bracket around the whereHas and the OrWherehas
$parts->where(function($q) use($text) {
$q->whereHas('details', function($query) use($text) {
$query->where('notes', 'LIKE', '%' . $text . '%');
});
$q->orWhereHas('classifier', function($query) use($text) {
$query->where('name', 'LIKE', '%' . $text . '%');
});
});
}
}
希望对您有所帮助
whereHas
Laravel 中的方法使用 MySQL 中的 EXISTS
。问题是,例如,当指定品牌和文本时,它会在文本存在的地方获取所有有或没有品牌的项目……但我需要,当指定品牌时,它只需要那些有品牌和文本的项目。
$parts = AutoPart\Part::has('classifier')->with(['details', 'classifier', 'order', 'place'])-> orderBy('id', 'desc');
if ($brand = $request->get('brand', FALSE)) {
$parts->whereHas('details', function($query) use($brand) {
$query->where('brand', '=', $brand);
});
}
if ($model = $request->get('model', FALSE)) {
$parts->whereHas('details', function($query) use($model) {
$query->where('model', '=', $model);
});
}
if ($text = $request->get('text', FALSE)) {
if (strlen($text) > 0) {
$parts->whereHas('details', function($query) use($text) {
$query->where('notes', 'LIKE', '%' . $text . '%');
});
$parts->orWhereHas('classifier', function($query) use($text) {
$query->where('name', 'LIKE', '%' . $text . '%');
});
}
}
将最后一个条件更改为
if ($text = $request->get('text', FALSE)) {
if (strlen($text) > 0) {
// This will put a bracket around the whereHas and the OrWherehas
$parts->where(function($q) use($text) {
$q->whereHas('details', function($query) use($text) {
$query->where('notes', 'LIKE', '%' . $text . '%');
});
$q->orWhereHas('classifier', function($query) use($text) {
$query->where('name', 'LIKE', '%' . $text . '%');
});
});
}
}
希望对您有所帮助