2017-09-08 62 views
5

這個問題已經被問到here,但它沒有收到任何答案。現在我面臨同樣的問題,但是在laravel 5.4中。我有一個型號Book,型號ReadingSession和型號Comment。一本書有許多閱讀會議,並有許多意見,但閱讀會議也可以有評論。所以,我有我的關係定義如下:在子模型中使用多態關係導致無限循環?

book.php中

protected $with = [ 
    'author', 
    'readingSessions', 
    'userRating', 
    'ratings', 
    'comments' 
]; 

public function users() 
{ 
    return $this->belongsToMany(User::class, 'user_book'); 
} 

public function author() 
{ 
    return $this->belongsTo(Author::class); 
} 

public function allReadingSessions() 
{ 
    return $this->hasMany(ReadingSession::class); 
} 

public function readingSessions() 
{ 
    return $this->hasMany(ReadingSession::class) 
       ->where('user_id', Auth::user()->id); 
} 

public function ratings() 
{ 
    return $this->hasMany(Rating::class); 
} 

public function userRating() 
{ 
    return $this->hasMany(Rating::class) 
       ->where('user_id', Auth::user()->id); 
} 

public function comments() 
{ 
    return $this->morphMany('App\Models\Comment', 'commentable'); 
} 

ReadingSession.php

protected $with = ['comments']; 

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 

public function book() 
{ 
    return $this->belongsTo(Book::class); 
} 

public function comments() 
{ 
    return $this->morphMany('App\Models\Comment', 'commentable'); 
} 

Comment.php

public function commentable() 
{ 
    return $this->morphTo(); 
} 

這些似乎產生了一個無限循環。任何人都可以暗示我我做​​錯了什麼?

回答

3

你可能會有一個無限循環的主要原因是,如果你試圖自動加載一個關係,而這種關係反過來試圖對以前的模型做同樣的事情。

付諸一個例子:

book.php中

protected $with = [ 
    'author', 
]; 

public function author() 
{ 
    return $this->belongsTo(Author::class); 
} 

Author.php

protected $with = [ 
    'books', 
]; 

public function books() 
{ 
    return $this->hasMany(Book::class); 
} 

在這種情況下,每次取一個作家時它會自動獲取他的書反過來將嘗試取回作者,並繼續...

另一件事這可能會發生,並且很難意識到在某些訪問器上使用$appends屬性時。如果試圖通過$appends自動將變量放入模型中,並且該訪問器以某種方式獲取關係或使用關係,則可能會再次出現無限循環。

例子: Author.php

protected $appends = [ 
    'AllBooks', 
]; 

public function books() 
{ 
    return $this->hasMany(Book::class); 
} 

public function getAllBooksAttribute() { 
    return $this->books->something... 
} 

在這種情況下,每個應用程序試圖時間解決您的作者模型,將取回書籍,這反過來將獲取的作者,這反過來將取這些書再次和上...

從您的片段,不清楚是什麼導致問題,但這個答案可能會給一些線索在哪裏搜索它。

爲了解決這個問題,你可能會刪除從$with關係和手動加載:$author->load('books')或 您也可以加載在這樣一個關係的關係,例如:$author->load('books', 'books.comments')Author::with('books', 'books.comments')->where...

這一切降低你想要實現的。所以你必須評估你應該自動加載的內容和內容。

在您的模型上自動加載關係時以及向$appends添加訪問器時,尤其是如果它們使用關係時要小心。這是一個很棒的功能,但有時候可能很難咬。