Laravel Eloquent:如何在序列化到Array/toJson时自动获取关系
我认为这适用于自动获取以及当我将对象序列化为JSON时,但是覆盖真的是执行此操作的正确方法吗?user
replies
toArray
<?php
class Post extends Eloquent
{
protected $table = 'posts';
protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');
public function user()
{
return $this->belongsTo('User');
}
public function replies()
{
return $this->hasMany('Post', 'parent_post_id', 'id');
}
public function toArray()
{
$this->load('user', 'replies');
return parent::toArray();
}
}