2017-10-13 69 views
-1

我有以下表:Laravel显示数据3表

flights(id, title, number) 
stations(id, title) 
flight_price(id, price, flight_id, stationA_id, stationB_id) 
flight_station(flight_id, station_id) 

flight_station是一个透视表。

我的模型:

class Flight extends Model 
{ 
    public function stations() 
    { 
     return $this->belongsToMany('App\Model\Station', 'flight_station', 'flight_id', 'station_id') 
    } 

    // To attach data 
    public function prices() 
    { 
     return $this->belongsToMany('App\Model\FlightPrice', 'flight_price', 'flight_id', 'stationA_id') 
      ->withPivot('price'); 
    } 

    public function price() 
    { 
     return $this->hasMany('App\Model\FlightPrice', 'flight_id'); 
    } 
} 

// Station 
class Station extends Model 
{ 
    public function flights() 
    { 
     return $this->belongsToMany('App\Model\Flight', 'flight_station', 'station_id', 'flight_id'); 
    } 


} 

class FlightPrice extends Model 
{ 
    protected $table = 'flight_price'; 

    public function flights() 
    { 
     return $this->belongsToMany('App\Model\Flight', 'flight_price'); 
    } 
} 

我需要下一个结果(通过ID飞行找到):

|stationA_id|stationA_title||stationB_id|stationB_title|price| 
+2

什么你“需要”是真的不清楚。请更准确地描述预期的结果。你能提供迄今为止所做的一些工作吗? – louisfischer

+0

如何获取数据并显示它。如何链接所有使用雄辩关系? –

+0

有一个非常好的[一系列免费视频Laravel Laraasts开始](https://laracasts.com/series/laravel-from-scratch-2017) – louisfischer

回答

0

比方说,你正试图找回这样的飞行:

$flight = Flight::with(['price', 'stations'])->find($id); 

这会返回一个Flight模型PriceStation型号因为you eager loaded the relationships

现在$flight->price将返回与Flight模型相关联的Price模型。如果它不是一个集合 - 我认为这是真实的 - foreach循环没有什么意义(或者至少不是你所期望的)。事实上,它将循环访问Model类(incrementing,exists,wasRecentlyCreatedtimestamps)的公共属性。

所以下面这段代码将返回4个布尔值。

foreach ($flight->price as $value) { 
    dump($value); 
} 

如果你想要回台标识符,该站冠军和价格为每个航班,然后也许尝试这样的事:

foreach ($flight->stations as $station) { 
    dump($station->id); 
    dump($station->title); 
} 

// I assume the Price model has an attribute named value 
dump($flight->price->value)