Laravel范围中的别名列



这是我的型号范围

public function scopeUser($query, $user_id)
{
    return $query->where('user_id', $user_id)
                ->select(['_id', 'company_name', 'location', 'template_id', 'current_theme_id', 'site_url', 'site_path', 'addons']);
}

我想要的是用theme_id作为别名来代替current_theme_id

已尝试搜索解决方案,但所有主题都基于数据库查询。

感谢

将"current_theme_id"替换为"current_tcheme_id as theme_id",如下所示。

public function scopeUser($query, $user_id)
{
    return $query->where('user_id', $user_id)
                ->select(['_id', 'company_name', 'location', 'template_id', 'current_theme_id as theme_id', 'site_url', 'site_path', 'addons']);
}

在您的模型中,添加:

protected $appends = ['theme_id']
public function getThemeIdAttribute()
{
    return $this->current_theme_id;
}

文件:https://laravel.com/docs/5.1/eloquent-mutators#accessors-和突变体

在您的评论中:

我没有得到任何错误,但结果中没有current_theme_idtheme_id。这些记录正在以良好的返回

我怀疑列current_theme_id是否列在Model的$fillable属性中。如果已经列出,请尝试以下建议。

这可能只是一个变通办法,使用selectRaw方法

public function scopeUser($query, $user_id)
{
    return $query->where('user_id', $user_id)
                 ->selectRaw('*, current_theme_id AS theme_id')
                 ->select([
                     '_id', 'company_name', 'location',
                     'template_id', 'site_url', 'site_path',
                     'addons', 'theme_id'
                 ]);
}

您可以使用此代码。

public function scopeUser($query, $user_id)
{
    return $query->where('user_id', $user_id)
   ->selectRaw('_id, company_name, location, template_id, current_theme_id as theme_id, site_url, site_path, addons');
}

最新更新