EloquentのPolymorphic RelationsでHogeとFugaを使い分けているデータがあるとします。
hoge
id | name | number |
---|---|---|
1 | hoge | 0 |
```php | ||
<?php | ||
namespace App; | ||
use Illuminate\Database\Eloquent\Model; | ||
class Hoge extends Model | ||
{ |
public function base() { return $this->morphMany(Base::class, 'ref'); }
}
### fuga |id|name|text| |:--|:--| |1|fuga|a| ```php <?php namespace App; use Illuminate\Database\Eloquent\Model; class fuga extends Model { public function base() { return $this->morphMany(Base::class, 'ref'); } }
base
id | ref_id | ref_type |
---|---|---|
1 | 1 | Hoge |
2 | 1 | Fuga |
```php | ||
<?php | ||
namespace App; | ||
use Illuminate\Database\Eloquent\Model; | ||
class Base extends Model | ||
{ |
public function ref() { return $this->morphTo(); }
}
このとき、withメソッドを使わずBaseを得たときの挙動はこうなります。 ```php $base_list = Base::all(); // [ // ['id' => 1, 'ref_id' => 1, 'ref_type' => 'Hoge'], // ['id' => 2, 'ref_id' => 1, 'ref_type' => 'Fuga'] // ]
さらに、withを使うとこうなります。
php
1$base_list = Base::with(['ref'])->all(); 2// [ 3// ['id' => 1, 'ref_id' => 1, 'ref_type' => 'Hoge', 'ref' => [id => 1, 'name' => 'hoge', 'number' => 0]], 4// ['id' => 2, 'ref_id' => 1, 'ref_type' => 'Fuga', 'ref' => [id => 1, 'name' => 'fuga', 'text' => 'a']], 5// ]
ここまではいいのですが、例えばHogeにだけ新たにImageモデルのリレーションを加えたとします。
image
id | hoge_id | path |
---|---|---|
1 | 1 | image.jpg |
php
1<?php 2namespace App; 3use Illuminate\Database\Eloquent\Model; 4class Image extends Model 5{ 6 public function hoge() { 7 return $this->belongsTo(); 8 } 9}
Hoge(改変)
php
1<?php 2namespace App; 3use Illuminate\Database\Eloquent\Model; 4class Hoge extends Model 5{ 6 public function base() { 7 return $this->morphMany(Base::class, 'ref'); 8 } 9 public function images() { 10 return $this->hasMany(Image::class); 11 } 12}
このあと、HogeのImageも欲しいので以下のようにwithを書き直すとエラーになります。
php
1$base_list = Base::with(['ref', 'ref.images'])->all(); 2// Hogeにはimagesがあるが、Fugaにはimagesのリレーションがないのでエラー
当たり前だ、と言われればそれまでなのですが、「あったら取る」「なければnull、またはプロパティ自体が無い」状態のデータが取得したいのです。なんとか方法はないでしょうか。
試したこと
- Hogeモデルのappendsにimageを加え、getImageAttributeを実装する
php
1class Hoge extends Model 2{ 3 public function base() { 4 return $this->morphMany(Base::class, 'ref'); 5 } 6 public function images() { 7 return $this->hasMany(Image::class); 8 } 9 protected $appends = ['images']; 10 public function getImagesAttribute($value) { 11 return $this->images; // なぜかここでimagesというattributeは無いとエラーになる。 12 // なお外部から$hoge->imagesとアクセスした場合はエラーにならない 13 } 14}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/04 02:15