Ron*_*son 22 php laravel eloquent laravel-4
我认为这可以自动获取user
,replies
当我将对象序列化为JSON时,但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();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 46
使用,而不是覆盖toArray()
加载用户和回复$with
.
这是一个例子:
<?php
class Post extends Eloquent
{
protected $table = 'posts';
protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');
protected $with = array('user', 'replies');
public function user()
{
return $this->belongsTo('User');
}
public function replies()
{
return $this->hasMany('Post', 'parent_post_id', 'id');
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您应该toArray()
在您的控制器中使用,而不是您的模型,如下所示:
Post::find($id)->toArray();
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
小智 5
由于实在太多,我必须提交新的答案。对于那些像我一样在Google上发现此问题的人来说,一种更合适的方法是避免不必要的使用protected $with
,而是将该with()
调用移至您的检索中。
<?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');
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据需要修改Post调用以进行预加载:
Post::with('user','replies')->find($id)->toArray();
Run Code Online (Sandbox Code Playgroud)
这样,您无需每次获取记录时都不需要包含不需要的数据。