Laravel - 从关系中汲取领域

时间:2018-05-28 06:05:13

标签: php laravel eloquent

我是laravel和php的新手,现在我想创建一个休息api 我有这个问题:

 $questions = Question::with(
 array('picture' => function($query){     
      $query>select('question_id','picture_name')>pluck('picture_name')>all();
     },
       'user'=>function($query){
      $query->select('id','image','name');
     }))->get()->toArray();

我的查询返回此json:

{
"questions:": [
    {
        "id": 1,
        "title": "23",
        "caption": "last",
        "address": "lsdbabfd",
        "picture": [
            {
                "question_id": 1,
                "picture_name": "1527484678.jpg"
            },
            {
                "question_id": 1,
                "picture_name": "1527485120.jpg"
            }
        ],
        "user": {
            "id": 1,
            "image": "defaultPicture",
            "name": "alex"
        }
    }
  ]
}

但我想要这个json:

{
"questions:": [
    {
        "id": 1,
        "title": "23",
        "caption": "last",
        "address": "lsdbabfd",
        "picture": [
            "1527484678.jpg",
            "1527485120.jpg"
        ],
        "user": {
            "id": 1,
            "image": "defaultPicture",
            "name": "alex"
        }
    }
  ]
}

我该怎么做? 我已经尝试用Laravel pluck方法和Eloquent Mutators

来做到这一点

1 个答案:

答案 0 :(得分:0)

您可以添加属性方法

class Question extends Model
{
    ...
    protected $appends = ['pictures'];
    public function getPicturesAttribute()
    {
        return $this->pictures->pluck('picture_id');
    }
}