简体   繁体   English

Laravel查询:每个选择的不同where子句

[英]Laravel query: Different where clauses for each select

I'm wondering, if there is a way to declare different where clauses for each select. 我想知道,是否有一种方法可以为每个选择声明不同的where子句。

Here is what I want to do: My Database looks like this: 这是我想做的事情:我的数据库如下所示: 数据库示例

with the columns "visible..." indicating, if I want to read out the related value or not. 带有“ visible ...”列,表示是否要读出相关值。 So if "visible_mobile" says "0", I don't want to read out the column "mobile". 因此,如果“ visible_mobile”说“ 0”,则我不想读出“ 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: 编辑:我试图获得的输出应该看起来像这样链接: 在此处输入图片说明

Using selectRaw() along with MySQL's IF function, you could do something like this: 结合使用selectRaw()和MySQL的IF函数,您可以执行以下操作:

$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: 由于您将laravel与Eloquent结合使用,一种更好的方法是在模型上为移动电话和出生日期字段定义访问器,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM