首先,让我解释一下我的数据库模式。如何在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在里面。如果无论如何也要将组件的名称添加到它,它将适合我的需要。
哪里是你的PARENT_ID?如果你想访问它,你需要在你的表中有一个parent_id ... –
父ID是在由Laravel中的多对多关系创建的名为component_codes的数据透视表中。无论如何,我有代码模式访问它吗? – pedropeixoto