Join 检索数据透视表在单个表中引用的两个外部表中包含的数据

Join 检索数据透视表在单个表中引用的两个外部表中包含的数据,join,eloquent,pivot,Join,Eloquent,Pivot,也许有了这张照片,我可以把自己说清楚。 我有user表和owned\u items表 拥有的项目通过users\u owned\u itempivot表附加到用户 用这种雄辩的方法 $owned_items = Auth::user()->owned_items->toArray(); 我得到的是所拥有的\u项目表中包含的“项目类型\u id”和“项目颜色\u id”。 但是我真正需要的是item\u类型和item\u颜色表中包含的实际数据,问题是:如何获取该数据而不是外键id p

也许有了这张照片,我可以把自己说清楚。 我有
user表
owned\u items表
拥有的项目通过
users\u owned\u item
pivot表附加到用户

用这种雄辩的方法

$owned_items = Auth::user()->owned_items->toArray();
我得到的是
所拥有的\u项目
表中包含的“项目类型\u id”和“项目颜色\u id”。 但是我真正需要的是
item\u类型
item\u颜色
表中包含的实际数据,问题是:如何获取该数据而不是外键id

p.s.“用户拥有的项目”表中“项目id”的varchar类型只是一个错误,当然是一个INT。

另外,请让我知道这些关系是否正确:

用户模型中

public function owned_items(){
        return $this->belongsToMany('App\owned_items')->withTimestamps();
    }
拥有的\u项目中模型

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

    }
public function Owned_item(){
        return $this->belongsToMany('App\Owned_item');
    }
public function Owned_item(){
            return $this->belongsToMany('App\Owned_item');
        }
项目类型中模型

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

    }
public function Owned_item(){
        return $this->belongsToMany('App\Owned_item');
    }
public function Owned_item(){
            return $this->belongsToMany('App\Owned_item');
        }
项目中,使用颜色模型

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

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

考虑到我描述的模型结构,我找到了一种方法。这样我可以访问数据。如果有其他更简单的方法,请告诉我:

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"
  ]
]
所以我可以把这个结果传递给我的观点,对吗?我想不出任何其他方法来创建包含所需数据的数组。雄辩能让事情变得更好吗