質問

多態的な 1 対 1 の関係 (has_one とbelongs_to に相当する多態的) をセットアップしようとしています。 Address 1 つのアドレスが必要なモデルが他にもいくつかあります。しかし、ドキュメントの文言に混乱しています。私は見たことがあります morphMany 方法ですが、私の質問は次のとおりです。使ったほうがいいですか morphMany アドレスを 1 つだけ指定したい場合でも、または morphOne 私が使用すべき方法は何ですか?

編集:私の Address 視覚化を容易にするために、モデルには次のフィールドがあります。

Schema::create('addresses', function ($table)
{
    $table->increments('id');
    $table->string('street');
    $table->string('street_more')->nullable();
    $table->string('city');
    $table->string('state')->nullable();
    $table->string('country');
    $table->string('postal_code');
    $table->integer('addressable_id');
    $table->string('addressable_type');
});
役に立ちましたか?

解決

はい、あります モーフワン この場合に使用するべき方法は次のとおりです。 https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L811 .

また、使用することもできます

$table->morphs('addressable');

の代わりに

$table->integer('addressable_id');
$table->string('addressable_type');

私は L4 のカスタム パッケージで morphOne を使用しましたが、非常にうまく機能します。

他のヒント

これを試してみてください。サポートされていない morphOne よりも優れていると思います。

  public function address()
  {
      return $this->hasOne('App\Address', 'addressable_id','id')
                   ->where('addressable_type', 'App\Model');
  }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top