laravel不同键有很多关系

时间:2018-11-19 11:02:10

标签: laravel eloquent relationship

我想要hasMany关系中的数据作为对象而不是数组返回。 我所拥有的是: 调查->问题->答案->信息 这种关系很好,但是我得到的信息是这样的:

[{
    "id": 1,
    "name": "some_info",
    "value": "this is just some info",
    "survey_answer_id": answer_id
},
{
    "id": 2,
    "name": "more_info",
    "value": "this is some more info",
    "survey_answer_id": answer_id
}]

我希望它作为这样的对象返回:

{
    "some_info": "this is just some info",
    "more_info": "this is some more info"
}

我做了一些研究,但没有发现任何可以帮助我的东西。 我在Answers类中定义了如下信息:

public function info()
{
    return $this->hasMany('App\SurveyAnswerInfo')->orderBy('priority');
}

这就是我的加载方式

$survey = Survey::find($id);
$survey->load('questions', 'questions.answers', 'questions.answers.info');

2 个答案:

答案 0 :(得分:0)

在您的答案模型中:

// this will append some_info and more_info in your answer object

public $appends=['some_info','more_info'];


public function info()
{
    return $this->hasMany('App\SurveyAnswerInfo')->orderBy('priority')
}

public function getSomeInfoAttribute(){
return $this->info->pluck('value')->toArray();
}

public function getMoreInfoAttribute(){
return $this->info->pluck('value')->toArray();
}

在您的控制器中,您可以访问:

$some_info=Survey->Question->Answer->some_info;
$more_info=Survey->Question->Answer->more_info;

答案 1 :(得分:0)

我认为您应该在您的Answer模型中添加访问器方法:

public function getPreparedInfoAttribute(){
    return (object)$this-info->pluck('value', 'name')->toArray();
}

并访问它:

$survey->question->answer->prepared_info->some_info;
$survey->question->answer->prepared_info->more_info;

您应该添加一些对null的检查。