Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Laravel中将动态附加添加到模型_Php_Json_Laravel_Laravel 4 - Fatal编程技术网

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

Php 如何在Laravel中将动态附加添加到模型,php,json,laravel,laravel-4,Php,Json,Laravel,Laravel 4,首先,让我解释一下我的DB模式 这个问题的重要部分是我有3个表: 组成部分 代码 组件代码(充当两者之间关系的透视表) 组件和代码处于多个关系中 我在/components/index/路径中设置了restful API,如下所示: { "id": "49", "name": "Gloves", "thumb": "img\/product.jpg", "filter_id": "9", "active": "1", "created_at

首先,让我解释一下我的DB模式

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

  • 组成部分
  • 代码
  • 组件代码(充当两者之间关系的透视表)
组件和代码处于多个关系中

我在
/components/index/
路径中设置了restful 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对象附加两个值,该子json对象将具有该对象的父对象的值。在本例中,我需要“code”数组具有值
“name”:“手套”
“拇指”:“img\/product.jpg”
。本质上是复制它的父级数据

到目前为止,我有:

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

}

这是一个多对多关系,因此您可能有许多记录,但您可以这样做,以获得第一条记录:

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
}

你父母的身份证在哪里?如果要访问表,则需要在表中包含一个父项id…父项id位于名为component_codes的透视表中,该透视表是由Laravel中的多对多关系创建的。在代码模型中,我是否可以访问它?OláAntonio。我编辑了这篇文章,试图更好地解释我的处境,谢谢你的提示。关于您的答案,我在您的第一个解决方案中得到了“尝试获取非对象的属性”,当我尝试以下操作时,得到了一个空数组: