[英]How can I write given SQL query in Laravel
如何在 Laravel 查询中写下 SQL 查询
SELECT
notifications.*,
if(notifications.branchID=0, 'All', (
select
group_concat(name)
from
branches
where
find_in_set(id,notifications.branchID)
)) as brcName
FROM
notifications
WHERE
id = 2
询问:
SELECT
notifications.*,
if(notifications.branchID=0, 'All', (
select
group_concat(name)
from
branches
where
find_in_set(id,notifications.branchID)
)) as brcName
FROM
notifications
WHERE
id = 2
查询生成器:
DB::table('notifications')
->select('notifications.*')
->addSelect(DB::raw("if(notifications.branchID=0, 'All', (
select
group_concat(name)
from
branches
where
find_in_set(id,notifications.branchID)
)) as brcName"))
->where('id', 2);
Eloquent model:
class Notification extends Model
{
public function getBrcNameAttribute()
{
if ($this->branchID === 0) {
return 'All';
}
return $this->branches()->select('group_concat(name) AS brcName')->first()->brcName;
}
public function branches()
{
return $this->hasMany(\App\Models\Branch::class);
}
}
$id = some_id; $query = DB::select( DB::raw("SELECT notifications.*, if(notifications.branchID=0,'All',(select group_concat(name) FROM branches where find_in_set(id,notifications.branchID))) as brcName FROM notifications WHERE id = :id"), array('id' => $id) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.