Reputation: 2767
I am storing a where clause in a variable
if($condition === 1) {
$whereClause = ['mID' => NULL, 'qid' => $listing->lID, 'deleted' => false];
}
else {
$whereClause= ['mID' => $member->mID, 'qid' => $listing->lID, 'deleted' => false];
}
And I get the collection via
$collection = Model::where($whereClause)
BUT on the first condition, I actually want the mID
to be either 0 or NULL, I want to retrieve items where mID can be 0 or NULL, so I want orWhere clause, which I did use as shown below, but this does not work, gives an error of memory exhausted so something went wrong
if($condition === 1) {
$whereClause = ['mID' => NULL, 'qid' => $listing->lID, 'deleted' => false];
$orWhereClause = ['mID' => 0, 'qid' => $listing->lID, 'deleted' => false];
$collection = Model::where($whereClause)->orWhere($orWhereClause)
}
else {
$whereClause= ['mID' => $member->mID, 'qid' => $listing->lID, 'deleted' => false];
$collection = Model::where($whereClause)
}
Any ideas of how I can achieve this sort of where condition
Upvotes: 1
Views: 2147
Reputation: 12899
Except for the missing of ";", i think that you should implement it in this way:
$whereClause = [['mID', NULL], ['qid' , $listing->lID] , ['deleted', false]];
$orWhereClause = [['mID', 0], ['qid' , $listing->lID] , ['deleted', false]];
$collection = Model::where($whereClause)->orWhere($orWhereClause);
and if you need other condition, just push an array in the right array where the first parameter is the field and the second the value, or first parameter is the field, the second the operator and the third the value
Upvotes: 2
Reputation: 1446
Miken32 is correct, but the code could be written in a single query instead of adding the where()
in an if/else statement:
$collection = Model::where('qid', $listing->lID)->where('deleted', false)
->when($condition === 1, function($q){
$q->whereIn('mID', [0, NULL]);
})->when($condition !== 1, function($q){
$q->where('mID', $member->mID);
});
Upvotes: 1
Reputation: 42676
This seems like the easiest method. Chaining where()
methods is the same as passing them in as an array.
$collection = Model::where('qid', $listing->lID)->where('deleted', false);
if($condition === 1) {
$collection = $collection->whereIn('mID', [0, NULL]);
}
else {
$collection = $collection->where('mID', $member->mID);
}
(Note that according to the documentation, if you wanted to pass an array to the where()
method, you were doing it wrong.)
Upvotes: 2