2017-10-13 9 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

ララカストのララベルで始まる本当に良いビデオがあります(https://laracasts.com/series/laravel-from-scratch-2017) – louisfischer

答えて

0

は、あなたがこのような飛行を取得しようとしているとしましょう:

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

モデルを返します。PriceStationモデルです。you eager loaded the relationshipsです。

今すぐ$flight->priceFlightモデルに関連付けられたPriceモデルを返します。もしそれがコレクションではない - 私が信じている - foreachループはほとんど意味がありません(少なくともあなたが期待するものではありません)。実際には、Modelクラス(incrementingexistswasRecentlyCreatedおよびtimestamps)のパブリック属性をループします。

したがって、次のコードは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)