如何在Laravel中添加动态附加到模型

时间:2014-02-17 16:11:33

标签: php json laravel laravel-4

首先,让我解释一下我的数据库架构。

这个问题的重要部分是我有3个表:

  • 部件
  • component_codes(充当两者之间关系的数据透视表)

组件和代码属于ManyToMany关系。

我在/components/index/路线中设置了相似的API,如下所示:

  {
    "id": "49",
    "name": "Gloves",
    "thumb": "img\/product.jpg",
    "filter_id": "9",
    "active": "1",
    "created_at": "2014-01-10 17:45:00",
    "updated_at": "2014-01-10 17:45:00",
    "codes": [
      {
        "id": "4",
        "code": "asd123",
        "specs": "10x10cm",
        "packing": "100",
        "active": "1",
        "created_at": "2014-01-06 16:19:26",
        "updated_at": "2014-01-06 16:19:26",
        "pivot": {
          "component_id": "49",
          "code_id": "4"
        }
      }
  }

我现在想要将两个值附加到“codes”子json对象,该对象将具有该对象的父级的值。在这种情况下,我需要“代码”数组的值为"name": "Gloves""thumb": "img\/product.jpg"。基本上复制了它的父母的数据。

到目前为止,我有这个:

模型/ Code.php

<?php

class Code extends Eloquent {
    protected $table = 'codes';
    protected $appends = array('parent_name', 'parent_img_url');

    protected $guarded = array();

    public static $rules = array();

    public function components()
    {
        return $this->belongsToMany('Component', 'component_codes', 'component_id', 'code_id');
    }

    public function getParentNameAttribute()
    {
        $parent = Component::find(50);
        return $parent->name_en;
    }

    public function getParentImgUrlAttribute()
    {
        $parent = Component::find(50);
        return $parent->thumb;
    }

}

这可以按预期工作,但它不是动态的,组件的ID是硬编码的(即:50)。我需要这个是相关组件的ID。

希望我明确表示,如果没有,请在评论中告诉我。

编辑:另一种解决方案是将这些值添加到laravel创建的数据透视表中。现在只有component_id和code_id。如果无论如何都要添加组件的名称,它也符合我的需要。

1 个答案:

答案 0 :(得分:0)

这是一个多对多关系,所以你可能有很多记录,但你可以这样做,以获得第一个:

public function getParentNameAttribute()
{
    $parent = $this->components()->first();

    return $parent->name_en;
}

您可能需要更好地解释您的结构/架构,以便此处的人员了解您的需求。

是没有意义的
Component::find($id);

从多个表中返回一个名称。

这是你处理多对多表格的方式:

public function getWhateverYouNeed()
{
    foreach($this->components as $component)
    {
        // do whatever you need with them
    }

    /// return whatever you need
}