2017-10-13 141 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)