【问题标题】:How to rename relation function in eloquent?如何在 eloquent 中重命名关系函数?
【发布时间】:2018-03-20 17:59:04
【问题描述】:

我使用 Laravel 5.3。这是我的查询,我希望在结果数组中将“children_rec”重命名为“node”。

 $boxes = Boxes::with('children_rec')
                ->whereNull('box_id')
                ->with('position')
                ->get()
                ->toJson(128);

更新: 关系代码:

public function child()
{
    return $this
        ->hasMany('PTA_OIMS\Boxes', 'box_id');
}

public function children_rec()
{
    return $this->child()
        ->with('children_rec')
        ->with('position');
}

谢谢

【问题讨论】:

  • 返回结构是什么样的?为什么不能直接操作数组?
  • @tadman:结果结构:pastebin.com/NFfWS0s2
  • 编辑您的问题以包含任何相关代码,请不要将其添加为杂乱的评论。
  • 也许这会有所帮助:stackoverflow.com/questions/25549526/…
  • 你可能需要使用witheloquent

标签: php laravel eloquent


【解决方案1】:

我认为 Laravel 不支持对关系进行别名处理。

您应该将您的关系重命名为您想要的名称:

public function node()
{
    return $this->child()
        ->with('node')
        ->with('position');
}

那么你可以这样称呼它:

$boxes = Boxes::with('node')
               ->whereNull('box_id')
               ->with('position')
               ->get()
               ->toJson(128);

【讨论】:

    【解决方案2】:

    使用属性访问器隐藏关系,然后在结果中显示访问器,例如:

    public function getNodeAttribute() {
      return $this->children_rec;
    }
    protected $hidden = array('children_rec');
    protected $appends = array('node');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-12
      • 2021-03-20
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多