我正在制作一个房地产销售网站。属性(property)可以是房子、公寓、商店等......
我有这样的关系:
模型://属性
class Imovel extends Model...
public function moradia(){
return $this->hasOne(Moradia::class);
}
public function apartamento(){
return $this->hasOne(Apartamento::class);
}
//公寓
public function imovel(){
return $this->belongsTo(Imovel::class);
}
//房子
public function imovel(){
return $this->belongsTo(Imovel::class);
}
迁移:
//属性
Schema::create('imoveis', function (Blueprint $table) {
$table->increments('id');
$table->integer('tipoImovel_id');
$table->string('finalidade',20);
$table->string('titulo',100);
$table->date('data')->nullable();
$table->integer('concelho_id');
$table->string('freguesia',50);
$table->string('rua',150);
$table->decimal('long', 10, 7)->nullable();
$table->decimal('lat', 10, 7)->nullable();
$table->boolean('destaque');
$table->boolean('estado')->default(true);
$table->string('descricao',500);
$table->string('preco',40);
$table->integer('empresa_id')->default(1);
$table->timestamps();
//房子
Schema::create('moradias', function (Blueprint $table) {
$table->integer('imovel_id');
$table->integer('nrPisosConstrucao');
$table->integer('nrWcs');
$table->integer('areaConstrucao');
$table->integer('areaTerreno');
$table->smallInteger('anoConstrucao');
$table->timestamps();
//公寓
Schema::create('apartamentos', function (Blueprint $table) {
$table->integer('imovel_id');
$table->integer('nrQuartos');
$table->integer('nrWcs');
$table->integer('nrPisosEdifio');
$table->integer('areasAcessorias');
$table->integer('areasHabitacionais');
$table->smallInteger('anoConstrucao');
$table->timestamps();
我的问题是:我如何知道该特性是房子、公寓还是商店......?
我有所有属性的列表,要编辑我该怎么办?我怎么知道它是哪种属性?
谢谢
最佳答案
检查 houses 或 apartments 表中是否有相关记录。因此,例如,如果 houses 表中没有相关记录,您将为 $impovel->moradia()
获取 null。
例如:
$imovel = App\Imovel::find($id);
if(!is_null($imovel->moradia())) {
// Property is a house
}
编辑:
我认为您最好在属性表中有列 -> property_type
。这可以取值“house”、“apartment”、“shop”等。
这将有助于轻松地仅选择住宅属性(property)/公寓属性(property)。
此外,您还可以使用一种关联方法:
public function attributes(){
if($this->type == 'house') {
return $this->hasOne(Moradia::class);
}
if($this->type == 'apartments') {
return $this->hasOne(Apartamento::class);
}
}
你可以这样做:$imovel->attributes()
,这将给出相应的属性属性。
关于php - Laravel- 在多个表中搜索一个 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42748624/