我試圖建立一個過濾函式,根據用戶選擇的特征回傳一個交易所的串列。每個特征都有一個獨特的slug,$featureSlugs包含這些slugs(字串)的陣列。
$featureSlugs = ['security'/span>, 'mobile-app', '2FA'] 。
$exchanges = Exchange:: whereHas('features', function($q) use ($featureSluggs) {
$q->where('slug', $featureSlugs) 。
})->get()。
非常奇怪的是,這個查詢對1個或2個特征有效,但超過2個就停止作業,不再過濾。
我希望過濾器的范圍越來越窄,因此對每個特征使用多個where陳述句,只回傳具有用戶選擇的所有特征的交換。這是我正在嘗試的代碼,它沒有起作用,但我認為它展示了我想做的事情:
$exchanges = Exchange:: whereHas('features', function($q) use ($featureSluggs) {
foreach($featureSlugs as $featureSlug)
{
$q->where('slug', $featureSlug) 。
}
})->get()。
我如何為陣列中的每個featureSlug放置多個where陳述句?
uj5u.com熱心網友回復:
你的方向是正確的。你只需要使用whereIn或orWhere
$exchanges = Exchange:: whereHas('features', function($q) use ($featureSluggs) {
$q->whereIn('slug', $featureSlugs) 。
//這個當然不是最佳選擇。
foreach($featureSlugs as$featureSlug) {
$q->orWhere('slug', $featureSlug) 。
}
})->get()。
uj5u.com熱心網友回復:
用這種方式試試吧。
$featureSlugs = ['security'/span>, 'mobile-app', '2FA'] 。
$exchanges = Exchange:: whereHas('features', function ($query) 變數">$query) use ($featureSluggs) {
$query->distinct()->whereIn('slug', $featureSlugs) 。
}, '=', count($featureSlugs))-> get();
uj5u.com熱心網友回復:
你可以這樣做:
$featureSlugs = ['security'/span>, 'mobile-app', '2FA'] 。
$exchanges = Exchange:: whereHas('features', function($q) use ($featureSluggs) {
foreach($featureSlugs as $featureSlug)
{
$q->where('slug', $featureSlug) 。
}
})-with(['features'=> function($q) use ($featureSluggs) {
foreach($featureSlugs as $featureSlug)
{
$q->where('slug', $featureSlug) 。
}
}])->get()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306670.html
標籤:
上一篇:嗨,我正在嘗試顯示登錄用戶的資訊,但它不作業。我是php和mysqli的新手,所以對于任何愚蠢的錯誤我都很抱歉。
