1

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

0

3 Answers 3

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

This will include any records that have mID = 0 regardless of whether deleted = false or qid = $linting->lID.
@miken32 edited, please try and tell me what happens
amazing! workwell. thankyou!
1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.