異なるrelationをもつ場合にEager Loadを実現したい
下記のような関係においてLike Modelに関してEager Loadをします
$likes = Like::with([ 'likeable', 'likeable.user', 'likeable.user.userinfo', ])->get();
とすると
Call to undefined relationship [user] on model [App\Book].
とのエラーメッセージが出ます。これはBook Modelにはuser relationが存在しないからですが
Book Modelの時はeager loadのlikeabke.user,likeable.user.userinfoを読み込まないような処理の実装方法を教えていただきたいです.
#Modelの関係
php
1class Like extends Model 2{ 3 protected $fillable = [ 4 'user_id', 5 'likeable_type', 6 'likeable_id', 7 ]; 8 9 public function likeable() 10 { 11 return $this->morphTo(); 12 } 13 14 public function user() 15 { 16 return $this->belongsTo('App\User'); 17 } 18} 19
php
1class Reply extends Model 2{ 3 protected $fillable = [ 4 'replyable_id', 5 'replyable_type', 6 'user_id', 7 'body' 8 ]; 9 10 public function replyable() 11 { 12 return $this->morphTo(); 13 } 14 15 public function likes() 16 { 17 return $this->morphMany('App\Like','likeable'); 18 } 19 20 public function user() 21 { 22 return $this->belongsTo('App\User')->withDefault([ 23 'name' => 'ゲスト', 24 ]); 25 } 26}
php
1class Comment extends Model 2{ 3 protected $fillable = [ 4 'commentable_id', 5 'commentable_type', 6 'user_id', 7 'type', 8 'body', 9 ]; 10 11 public function commentable() 12 { 13 return $this->morphTo(); 14 } 15 16 public function replies() 17 { 18 return $this->morphMany('App\Reply','replyable'); 19 } 20 21 public function likes() 22 { 23 return $this->morphMany('App\Like','likeable'); 24 } 25 26 public function user() 27 { 28 return $this->belongsTo('App\User')->withDefault([ 29 'name' => 'ゲスト', 30 ]); 31 } 32}
php
1class Article extends Model 2{ 3 use \Conner\Tagging\Taggable; 4 5 protected $fillable = [ 6 'user_id', 7 'title', 8 'body', 9 'like_count', 10 ]; 11 12 public function user() 13 { 14 return $this->belongsTo('App\User'); 15 } 16 17 public function likes() 18 { 19 return $this->morphMany('App\Like','likeable'); 20 } 21 22 public function comments() 23 { 24 return $this->morphMany('App\Comment','commentable'); 25 } 26}
補足情報(FW/ツールのバージョンなど)
Laravel5.7
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/20 04:03