Reputation: 119
I'm making a property sales site. A property can be a house, an apartment, a shop, etc....
I have this relations:
Models: //Properties
class Imovel extends Model...
public function moradia(){
return $this->hasOne(Moradia::class);
}
public function apartamento(){
return $this->hasOne(Apartamento::class);
}
//Apartment
public function imovel(){
return $this->belongsTo(Imovel::class);
}
//House
public function imovel(){
return $this->belongsTo(Imovel::class);
}
Migrations:
//Property
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();
//house
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();
//apartment
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();
My question is: How will I find out if the property is a house, or apartment, or a shop ...?
I have the list of all the properties, to edit how do I? How do I know what kind of property it is?
Thanks
Upvotes: 1
Views: 488
Reputation: 3725
Check if a related record is there in either houses or apartments table. So for example if there are no related record in the houses table you will get null for $impovel->moradia()
.
Ex:
$imovel = App\Imovel::find($id);
if(!is_null($imovel->moradia())) {
// Property is a house
}
Edit:
I think you better have column in the properties table -> property_type
. This can take values 'house', `apartment', 'shop' etc.
This will help in easily selecting only house properties/apartment properties.
Besides you can have one relation method:
public function attributes(){
if($this->type == 'house') {
return $this->hasOne(Moradia::class);
}
if($this->type == 'apartments') {
return $this->hasOne(Apartamento::class);
}
}
And you can do: $imovel->attributes()
, this will give the corresponding property attributes.
Upvotes: 1