You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Eloquent查询时不使用Raw语句添加自定义合并列

实现方案

方案1:Eloquent访问器(最优解,完全无需自定义SQL)

这是最符合Laravel开发规范的实现方式,不需要修改任何查询代码,仅需在Activity模型中定义访问器,取值逻辑完全在框架层面处理:

Laravel 9+ 版本写法

// 引入Attribute类
use Illuminate\Database\Eloquent\Casts\Attribute;

// 在Activity模型类中添加该方法
protected function coolTitle(): Attribute
{
    return Attribute::make(
        get: fn (mixed $value, array $attributes) => trim($attributes['title']) === '' 
            ? $attributes['original_title'] 
            : $attributes['title'],
    );
}

Laravel 8及更早版本写法

// 在Activity模型类中添加该方法
public function getCoolTitleAttribute()
{
    return trim($this->attributes['title']) === '' 
        ? $this->attributes['original_title'] 
        : $this->attributes['title'];
}

如果需要cool_title字段默认随模型的数组、JSON输出一同返回,可以在模型中追加$appends配置:

protected $appends = ['cool_title'];

使用时直接读取模型属性即可:

echo $activity->cool_title;

方案2:查询阶段生成字段

如果你需要在SQL层面生成该字段(比如要对cool_title做排序、模糊搜索等操作),可以用selectRaw配合IF函数简化写法,比原有的CASE语句更简洁:

$activity = Activity::selectRaw('IF(TRIM(title) = "", original_title, title) as cool_title')->get();

注:目前Eloquent原生没有封装条件字段选择的方法,如果完全不允许使用任何Raw类方法,优先使用方案1的访问器实现。

内容的提问来源于stack exchange,提问作者Anibal Cardozo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:54:03