【问题标题】:Select a fake column in Laravel Eloquent在 Laravel Eloquent 中选择一个假列
【发布时间】:2019-01-01 22:11:12
【问题描述】:

我是否可以使用 Laravel Eloquent 从表中选择一个假列?

例如,table1 中有 column1 和 column2 列,但我也想显示我已经知道的类型。类似于:Select 'type1 as type', column1, column2 from table1;

如何使用 Eloquent 实现这一目标?

【问题讨论】:

  • 只需 select "known string" as type 与其他列,如果它是特定于条件的,则使用 where 子句。
  • 你需要它做什么?
  • 如果您使用迁移,您已经知道类型,您可以对其进行硬编码并保存查询。

标签: sql laravel eloquent


【解决方案1】:

选项1:

取回后在模型中设置即可:

$whatever = Model::all()->first();
$whatever->fakeit = 'till_you_make_it';
echo $whatever->fakeit 

'till_you_make_it'

选项 2:(更酷更 laravelish)

在您的模型中定义一个访问器(只需添加一个具有特定名称 getXXXXXAttribute 的公共函数,其中“XXXXX”是要伪造的列的名称,并使其返回您希望它具有的任何值。

class MyModel {
.
.
   public function getFakeitAttribute(){
        return "till_you_make_it";
   }
.
.
}

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 2021-12-24
    • 2018-12-07
    • 2013-06-10
    • 2016-11-05
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多