3 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
您將所有 where 語句括在括號(hào)中。我認(rèn)為您想要做的是將查詢的第一部分從 where 子句中拉出,以便您可以輕松地將該whereHas部分括在括號(hào)中。
// Initialise the model
$query = new Master;
// Start building the query
if ($request->filter == true) {
$query->where('user_id', Auth::user()->id);
}
if (!empty($request->area_from) && !empty($request->area_to)) {
// Wrap these in brackets so we don't interfare with the previous where
$query->where(function($query2) use ($request) {
$query2->whereHas('one', function ($query3) use ($request) {
$query3->whereBetween('area', [$request->area_from, $request->area_to]);
});
$query2->orWhereHas('two', function ($query3) use ($request) {
$query3->whereBetween('area', [$request->area_from, $request->area_to]);
});
}
}
$query->with(['one', 'two'])->paginate($request->item);

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以參考此鏈接創(chuàng)建合并關(guān)系
public function mergedOneAndTwo($value)
{
// There two calls return collections
// as defined in relations.
$onedata= $this->one;
$twodata= $this->two;
// Merge collections and return single collection.
return $onedata->merge($twodata);
}
并使用 whereHas('mergedOneAndTwo')

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個(gè)贊
使用更近的位置并在內(nèi)部設(shè)置條件可能會(huì)正常工作
$master = Master::with('one')->with('two');
$result = $master->where(function($subQuery)
{
$subQuery->whereHas('one', function ( $query ) {
$query->whereBetween('area', [$request->area_from, $request->area_to] ); //assuming $request->area_from, $request->area_to is range of value
})
->orWhereHas('two', function ( $query ) {
$query->whereBetween('area', [$request->area_from, $request->area_to] );
});
});
- 3 回答
- 0 關(guān)注
- 339 瀏覽
添加回答
舉報(bào)