gpt4 book ai didi

php - Laravel Eloquent : How to automatically fetch relations when serializing through toArray/toJson

转载 作者:IT王子 更新时间:2023-10-28 23:51:39 27 4
gpt4 key购买 nike

我认为这适用于在我将对象序列化为 JSON 时自动获取 userreplies,但覆盖 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();
}
}

最佳答案

不要覆盖 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');
}

}

另外,你应该在你的 Controller 中使用 toArray(),而不是你的模型,像这样:

Post::find($id)->toArray();

希望这对您有所帮助!

关于php - Laravel Eloquent : How to automatically fetch relations when serializing through toArray/toJson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21589622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com