我有以下表格:
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|
答案 0 :(得分:0)
假设您正在尝试检索这样的航班:
$flight = Flight::with(['price', 'stations'])->find($id);
这会返回Flight
模型 Price
和Station
模型,因为you eager loaded the relationships。
现在$flight->price
将返回与Price
模型关联的Flight
模型。如果它不是一个集合 - 我认为是真的 - foreach
循环没什么意义(或者至少不是你期望的那个)。实际上,它会循环遍历Model
类(incrementing
,exists
,wasRecentlyCreated
和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)