代码之家  ›  专栏  ›  技术社区  ›  oliverbj

PHP/Laravel-合并结果(模型关系)

  •  0
  • oliverbj  · 技术社区  · 7 年前

    First

    Second

    上面的问题是,它为数据库中的每个条目创建了一个新数组。

    我非常希望得到以下输出:

    Third

    Fourth

    区别在于:

    • Route

    • Carrier 下面的路线是一样的,那么它应该在那条路线下面 载体

    Controller.php :

    public function show()
        {
            $routes = Routes::where('id', '>=', 1)
            ->with('routeStops', 'getVessel')
            ->get()
            ->toArray();
    
            foreach ($routes as $key => $value) {
                echo '<h2>Route: ' . $value['origin'] . ' to ' . $value['destination'] . '</h2>';
                $carrier = Carriers::where('id', $value['get_vessel']['carriers_id'])->first()->name;
                echo 'Carrier: ' . $carrier . '';
                dump($value);
            }
    
        }
    

    这是我的模型:

    Routes.php

    /**
     * Get the route stop associated with this route.
     */
    public function routeStops()
    {
        return $this->hasMany('App\RouteStops', 'route_id');
    }
    
    /**
    * Get the vessel record associated with this route.
    */
    public function getVessel()
    {
        return $this->belongsTo('App\Vessels', 'vessel_id');
    }
    

    如何才能实现第二个期望输出?

    0 回复  |  直到 6 年前