2015-11-03 34 views
0

也许有了这张图片,我可以让自己清楚。 我有user tableowned_items table 所拥有的项目是使用这个雄辩的方法通过数据透视表检索单表中引用的两个外表中包含的数据

$owned_items = Auth::user()->owned_items->toArray(); 

我所得到的“item_type_id”连接到用户通过users_owned_item透视表

和“item_color_id“包含在owned_items表中。 我真正需要的是item_typesitem_colors表中包含的实际数据,问题是:如何获取该数据而不是外键标识?

p.s. user_owned_items表中的“item_id”的varchar类型只是一个错误,当然这是一个INT。

也请让我知道如果这些关系是正确的:

用户模式

public function owned_items(){ 
     return $this->belongsToMany('App\owned_items')->withTimestamps(); 
    } 
owned_items

模型

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'); 

    } 

ITEM_TYPE

model

public function Owned_item(){ 
     return $this->belongsToMany('App\Owned_item'); 
    } 

Item_color模型

public function Owned_item(){ 
      return $this->belongsToMany('App\Owned_item'); 
     } 

data in foreign tables

回答

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" 
    ] 
] 

这样我就可以通过这个结果,以我的看法,是正确的?我想不出任何其他方法用我需要的数据创建一个数组。雄辩是否允许更好的东西?