也许有了这张图片,我可以让自己清楚。
我有int
和user table
拥有的项目通过owned_items table
数据透视表
使用这种雄辩的方法
users_owned_item
我得到的是{{1>}表中包含的“ item_type_id ”和“ item_color_id ”。
我真正需要的是$owned_items = Auth::user()->owned_items->toArray();
和owned_items
表中包含的实际数据,问题是:如何获取该数据而不是外键ID?
P.S。 user_owned_items表中的varchar类型“item_id”只是一个错误,当然是INT。
另请告诉我这些关系是否正确:
用户模型 中的
item_types
own_items 模型中的
item_colors
在 Item_type 模型中
public function owned_items(){
return $this->belongsToMany('App\owned_items')->withTimestamps();
}
在 Item_color 模型中
public function user(){
return $this->belongsToMany('App\User');
}
public function Item_type(){
return $this->hasOne('App\Item_type');
}
public function Item_color(){
return $this->hasOne('App\Item_color');
}
答案 0 :(得分:0)
鉴于我所描述的模型结构,我找到了一种方法。这样我就可以访问数据了。如果有更简单的方法,请告诉我:
public function index()
{
$id = Auth::id();
$user = User::find($id);
$results = array();
foreach ($user->owned_item as $i) {
$results [] = array(
"type" => $i->Item_type->type,
"color" => $i->Item_color->color
);
}
dd ($results);
}
例如,这导致:
array:3 [▼
0 => array:2 [▼
"type" => "Type A"
"color" => "black"
]
1 => array:2 [▼
"type" => "Type B"
"color" => "red"
]
2 => array:2 [▼
"type" => "Type C"
"color" => "green"
]
]
所以我可以把这个结果传递给我,这是正确的吗?我想不出任何其他方法来创建一个包含我需要的数据的数组。雄辩是否允许更好的东西?