【问题标题】:How can I write given SQL query in Laravel如何在 Laravel 中编写给定的 SQL 查询
【发布时间】:2021-05-28 10:29:28
【问题描述】:

如何在 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

【问题讨论】:

  • 首先在 SQL RAW 查询中正确编写它,这样我们就可以将其“翻译”为 elloquent Buery Builder 或类似的东西......并格式化您的代码。
  • @hicham-o-sfh 这个东西会在 mysql 上返回完美的结果
  • 所以请提及您的 MySQL 版本,并发布您所有格式正确的代码。
  • 得到了解决方案老兄,干杯! ✔????解决方案是 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 通知 WHERE id = :id"), array( 'id' => $id, ));

标签: php mysql laravel eloquent


【解决方案1】:

查询:

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

雄辩的模型:

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

【讨论】:

  • 抛出错误 Facade\Ignition\Exceptions\ViewException 未定义属性:Illuminate\Database\MySqlConnection::$brcName
  • 如果你dd($this->branches()->select('group_concat(name) AS brcName')->first())会发生什么?
  • 找到了解决方案,非常感谢您的回答!
  • 这个也有效!让我们在那个帖子上打2个绿色勾号。 :D
【解决方案2】:
$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)
);

【讨论】:

  • 它有效,但它很难被称为“Laravel 解决方案”:D
  • CIAO,哥们儿,哥们儿急,我得去
猜你喜欢
  • 2016-04-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 2017-12-28
相关资源
最近更新 更多