2017-03-12 12 views
1

私は不動産販売サイトを作っています。Laravel-複数のテーブルでIDを検索

モデル://プロパティ

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(); 

私の質問は:プロパティがある場合はどのように見つけるだろう家、アパート、または店...?

私はどのように編集するために、すべてのプロパティのリストを持っていますか?それがどんな種類の財産であるかを私はどのように知っていますか?

おかげ

答えて

1

チェック関連レコードがどちらかの家やアパートのテーブルに存在する場合。たとえば、家のテーブルに関連するレコードがない場合、$impovel->moradia()の場合はNULLが返されます。

例:

$imovel = App\Imovel::find($id); 

if(!is_null($imovel->moradia())) { 
    // Property is a house 
} 

編集:

私はあなたが良好な特性表の列があると思う - >property_typeを。

これは、家のプロパティ/アパートメントのプロパティだけを簡単に選択するのに役立ちます。これは、 'house'、 'apartment'、 'shop'などの値を取ることができます。

あなたが1つのリレーション方式持つことができるほか:

public function attributes(){ 
    if($this->type == 'house') { 
     return $this->hasOne(Moradia::class); 
    } 

    if($this->type == 'apartments') { 
     return $this->hasOne(Apartamento::class); 
    } 
} 

そして、あなたが行うことができます:$imovel->attributes()を、これが対応するプロパティの属性を与えます。

+0

私の質問です:これは[link](https://gyazo.com/dde2e2e3fa8fe2227f5cce0fa6d61fad)のようです。私はボタンをクリックすると、家/アパートの詳細を表示する方法を教えてください。 –

+0

ええ、あなたの編集はおそらく私を助けるでしょう!ありがとう、私はそれを試してみると、私はいくつかのフィードバックを与えるだろう。 –

+0

申し訳ありませんが、初めてのPHPとLaravel:S –

関連する問題