[英]How to use the same eloquent query twice, but with one different where clause?
我有這個查詢:
User::leftJoin('friends', function ($join) {
$join->on('friends.user_id_1', '=', 'users.id')
->orOn('friends.user_id_2', '=', 'users.id');
})
->where(function ($query) use ($myID) {
// Group orwhere functions so the query builder knows these belong together
$query->where([
'friends.user_id_1' => $myID,
'friends.accepted' => true
])
->orWhere([
'friends.user_id_2' => $myID,
'friends.accepted' => true
]);
})
->where('users.id', '!=', $myID) // Exclude the user with id $myID
->get();
https://stackoverflow.com/a/41832867/5437864
我想兩次使用此查詢,但使用不同的where子句。 是否可以在不復制整個代碼的情況下重用此查詢? 如果是這樣,怎么辦?
$query = User::leftJoin('friends', function ($join) {
$join->on('friends.user_id_1', '=', 'users.id')
->orOn('friends.user_id_2', '=', 'users.id');
})
->where(function ($query) use ($myID) {
// Group orwhere functions so the query builder knows these belong together
$query->where([
'friends.user_id_1' => $myID,
'friends.accepted' => true
])
->orWhere([
'friends.user_id_2' => $myID,
'friends.accepted' => true
]);
});
在現有查詢中添加其他位置
$query->where('users.id', '!=', $myID)
$query->get();
查看此鏈接以獲取另一個示例
我使用了PHP clone keyword
。 我不確定這是否是最佳解決方案,但有幫助。 歡迎其他任何建議。
$friends_query = User::leftJoin('friends', function ($join) {
$join->on('friends.user_id_1', '=', 'users.id')
->orOn('friends.user_id_2', '=', 'users.id');
})
->where(function ($query) use ($myID) {
// Group orwhere functions so the query builder knows these belong together
$query->where([
'friends.user_id_1' => $myID,
'friends.accepted' => true
])
->orWhere([
'friends.user_id_2' => $myID,
'friends.accepted' => true
]);
});
$friends_me = clone $friends_query;
$friends_me = $friends_me->where('users.id', '!=', $myID);
$friends_others = clone $friends_query;
$friends_others = $friends_others->where('users.id', '=', $myID);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.