【问题标题】:Laravel - how to know if the attribute exists in relacional tableLaravel - 如何知道属性是否存在于关系表中
【发布时间】:2017-08-26 04:10:51
【问题描述】:

我正在做一个房地产销售网站,我要做一个高级搜索,例如卧室数量。

但是我有像商店这样没有卧室属性的属性,如何知道我必须搜索的每张桌子,比如公寓或房子。 我正在使用范围和属性的位置和类型工作正常。

我的属性模型

public function atributos(){
        //se for moradia
        if ($this->tipoimovel_id == 1) {
            return $this->hasOne(Moradia::class);
        }
        //se for apartamento
        else if ($this->tipoimovel_id == 2) {            
            return $this->hasOne(Apartamento::class);
        }
        //se for loja
        else if ($this->tipoimovel_id == 3) {
            return $this->hasOne(Loja::class);
        }
        //se for armazem
        else if ($this->tipoimovel_id == 4) {
            return $this->hasOne(Armazem::class);
        }
        //se for terreno para construção
        else if ($this->tipoimovel_id == 5) {
            return $this->hasOne(TerrenoConstrucao::class);
        }
        // se for terreno para outros fins
        else if ($this->tipoimovel_id == 6) {
            return $this->hasOne(TerrenoOutrosFins::class);
        }
    }      

仓库没有卧室数量

Schema::create('armazens', function (Blueprint $table) {
    $table->integer('imovel_id');           
    $table->integer('areaAcessoria');
    $table->integer('areaTotal');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

房子有

Schema::create('moradias', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('nrPisosConstrucao');
    $table->integer('nrQuartos');
    $table->integer('nrWcs');
    $table->integer('areaConstrucao');
    $table->integer('areaTerreno');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

我按卧室数量搜索的范围

public function scopeProcuraNrQuartos($query,$nrQuartos){
    if ($nrQuartos) $query->where( $this->atributos()->nrQuartos , '>=' , $nrQuartos);
} 

我知道这是错误的,但是存在一些验证以知道该属性是否存在于表中? 谢谢

【问题讨论】:

标签: php mysql laravel scope


【解决方案1】:

如果我没听错,你需要检查数据库中是否存在属性(列)?

如果是这样,你可以这样做:

Schema::hasColumn($model->getTable(), $column);

因此,在您的情况下,只需将此检查替换为

if ($nrQuartos) 

当然是你的模型和列名

原帖在这里:https://laracasts.com/discuss/channels/eloquent/test-attributescolumns-existence?page=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多