0

I'm wondering, if there is a way to declare different where clauses for each select.

Here is what I want to do: My Database looks like this: database Example

with the columns "visible..." indicating, if I want to read out the related value or not. So if "visible_mobile" says "0", I don't want to read out the column "mobile".

Of course I could do it by doing multiple queries like:

$userDetails1 = DB::table('user')
 ->select('mobile', 'id')
 ->where('user_id',  5)
 ->where('visible_mobile',  1)
 ->get();

$userDetails2 = DB::table('user')
 ->select('date_of_birth', 'id')
 ->where('user_id',  5)
 ->where('visible_date_of_birth',  1)
 ->get();

But I'm wondering if I could do this with just one query?

EDIT: the output I'm trying to get should look something linke this: enter image description here

3
  • Can you draw me a table (WITH column headers), showing an example output from this combined query you want?
    – Lee
    Aug 6, 2014 at 14:50
  • I added an example to my question.
    – LocalHorst
    Aug 6, 2014 at 15:09
  • why are you aiming for unnecessary complecity? Why not just ask all data and use it if flag is set? (can be done either with multiple queries or complex query that will return you NULL if visible is 0)
    – Imre L
    Aug 6, 2014 at 15:09

1 Answer 1

3

Using selectRaw() along with MySQL's IF function, you could do something like this:

$userDetails = DB::table('user')
 ->selectRaw('id, user_id, IF(visible_date_of_birth = 1, date_of_birth, NULL) as dob, IF(visible_mobile = 1, mobile, NULL) as mob')
 ->where('user_id',  5)
 ->get();

Since you're using laravel with Eloquent a better way to accomplish this would be to define an accessor for both your mobile and date of birth fields on your model, like this:

function getMobileAttribute()
{
    if($this->visible_mobile == 1){
        return $this->mobile;
    } else {
        return NULL;
    }
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.