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

To start, let me explain my DB schema.

The important part for this question is I have 3 tables:

  • components
  • codes
  • component_codes (that acts as a pivot table for the relationship between the two)

Components and Codes are in a ManyToMany relationship.

I've got restful API set up in the /components/index/ route that looks like this:

  {
    "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"
        }
      }
  }

I now want to append two values to the "codes" child json object which will have the value of that object's parent. In this case, I need the "codes" array to have the value "name": "Gloves" and "thumb": "img\/product.jpg". Essentially duplicating it's parent's data.

So far I have this:

models/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;
    }

}

This works as expected, but it's not dynamic, the ID of the component is hard coded in (ie: 50). I need this to be the ID of the component in question.

Hope I made myself clear, if not, please let me know in the comments.

Edit: Another solution would be to add those values to the pivot table laravel creates. Right now there's only the component_id and the code_id in it. If there's anyway to add a the component's name to it as well it would fit my needs.

It's a many to many relation, so you might have many records, but you can do this, to get the first one:

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

    return $parent->name_en;
}

You might need to explain better your structure/schema so people here understands what you need. Makes no sense a

Component::find($id);

To return a name from a many to many table.

This is how you deal with many to many tables:

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

    /// return whatever you need
}