代码之家  ›  专栏  ›  技术社区  ›  nowox

如何在雄辩的模型中选择原始列?

  •  0
  • nowox  · 技术社区  · 7 年前

    我想在我的雄辩模型中添加一个自定义列,例如:

    class Shape extends Eloquent
    {
        public function getAreaAttribute()
        {
            return $this->width * $this->height;
        }
    }
    

    它允许生成如下查询:

    Shape::where('area', '>', 42)->get();
    

    我能做的是:

    Shape::select(['*', DB::RAW('width * height AS area')])->where('area', '>', 42)->get();
    

    但这不在我的模型中。有没有可能得到类似于:

    class Shape extends Eloquent
    {
        public function getAreaColumn()
        {
            return DB::RAW('width * height AS area')
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Taha Paksu    7 年前

    您可以在迁移中定义这一点:

    $table->integer('area')->virtualAs('height * width');
    

    每次读取时生成,或

    $table->integer('area')->storedAs('height * width');
    

    如果希望在数据库中存储列,如果不希望生成始终保持不变。

    然后添加 area

        2
  •  -2
  •   Free Code    7 年前

    我希望这段代码能帮助你

    $result = DB::table('shape')
                     ->select(DB::raw('width * height AS area'))
                     ->where('area', '>', 42)
                     ->get();
    
    推荐文章