2014-02-17 26 views
1

首先,让我解释一下我的数据库模式。如何在Laravel中添加动态追加模型

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

  • 部件
  • component_codes(充当枢轴表两者之间的关系)

组件和代码处于ManyToMany关系。

我有宁静的API在/components/index/路线设置,看起来像这样:

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

我现在想两个值追加到“代码”孩子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在里面。如果无论如何也要将组件的名称添加到它,它将适合我的需要。

+0

哪里是你的PARENT_ID?如果你想访问它,你需要在你的表中有一个parent_id ... –

+0

父ID是在由Laravel中的多对多关系创建的名为component_codes的数据透视表中。无论如何,我有代码模式访问它吗? – pedropeixoto

回答

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 
} 
+0

OláAntonio。我编辑了OP,试图更好地解释我的情况,谢谢你的提示。关于您的答案,我在第一个解决方案中获得了“尝试获取非对象的属性”,并且在尝试此方法时获得了一个空数组:http://laravel.io/bin/a1vB – pedropeixoto