Laravel显示数据3表

时间:2017-10-13 10:08:46

标签: php mysql laravel laravel-5 eloquent

我有以下表格:

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 flight查找):

|stationA_id|stationA_title||stationB_id|stationB_title|price|

1 个答案:

答案 0 :(得分:0)

假设您正在尝试检索这样的航班:

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

这会返回Flight模型 PriceStation模型,因为you eager loaded the relationships

现在$flight->price将返回与Price模型关联的Flight模型。如果它不是一个集合 - 我认为是真的 - foreach循环没什么意义(或者至少不是你期望的那个)。实际上,它会循环遍历Model类(incrementingexistswasRecentlyCreatedtimestamps)的公共属性。

所以下面这段代码将返回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)