【问题标题】:Laravel show data 3 tableLaravel显示数据3表
【发布时间】:2017-10-13 10:08:46
【问题描述】:

我有以下表格:

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|

【问题讨论】:

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

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

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

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

现在$flight->price 将返回与Flight 模型关联的Price 模型。如果它不是一个集合 - 我相信这是真的 - 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多