[英]laravel foreign key to current table
我具有以下表結構,該結構允許用戶提交評論或對評論的回復:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->integer('model_id')->unsigned();
$table->integer('parent_comment_id')->unsigned();
$table->text('comment');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
$table->foreign('model_id')->references('id')->on('models')->onDelete('cascade');
$table->foreign('parent_comment_id')->references('id')->on('comments')->onDelete('cascade');
});
我有一個外鍵parent_comment_id
,它指向comments
表。 這表明該注釋(雖然仍然是注釋對象)屬於父注釋。
如何在模型中為注釋表(/App/Comment.php)定義這種關系?
您可以嘗試這樣的操作(在App\\Comment
模型中):
public function replies()
{
return $this->childComments()->with('replies');
}
public function childComments()
{
return $this->hasMany(Comment::class, 'parent_comment_id', 'id');
}
因此,您可以使用Comment::with('replies')
遞歸加載所有相關的答復。 您可能會因為關系中使用的兩個功能而感到困惑,這是因為一個答復可能包含其自己的答復,因此您需要一個遞歸關系。 因此, replies()
將使用其自己的回復加載所有回復。 您也可以查看我幾年前為Laravel - 4
寫的這篇文章 Laravel - 4
但想法是相同的。
// Another example could be something like this
$post = Post::with('comments.replies')->find(1); // Get Post with all comments with replies
注意:在這種情況下, Post
模型必須包含comments()
(hasMany)關系方法。
您可以執行以下操作:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function parentComment()
{
return $this->hasOne('App\Comment');
}
}
您可以在此文檔頁面中查看更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.