duanli9930 2017-10-13 10:08
浏览 7

Laravel显示数据3表

I have the following tables:

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 is a pivot table.

My models:

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');
    }
}

I need the next result (find by id flight):

|stationA_id|stationA_title||stationB_id|stationB_title|price|
  • 写回答

1条回答 默认 最新

  • dongzhao5970 2017-10-14 18:43
    关注

    Let's say you are trying to retrieve a flight like this:

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

    This returns a Flight model with the Price and Station models because you eager loaded the relationships.

    Now $flight->price will return the Price model associated with the Flight model. If it is not a collection - which I believe is true - the foreach loop has little meaning (or at least not the one you expect). In fact it will loop through the public attributes of the Model class (incrementing, exists, wasRecentlyCreated and timestamps).

    So the following piece of code will return 4 booleans.

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

    If you want to return the station identifiers, the station titles and the price for each flight then maybe try something like this:

    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)
    
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?