我的代码由Laravel + dingo构建。
我有两个模型是一对多的关系:
Reservation.php(大师)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Reservation extends Model
{
protected $table = 'dbo.Reservation';
public function hasManyReservationDetails()
{
return $this->hasMany('App\Models\ReservationDetail', 'ReservationID', 'ReservationID');
}
}
ReservationDetail.php(详情)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ReservationDetail extends Model
{
protected $table = 'dbo.ReservationDetail';
public function belongsToReservation()
{
return $this->belongsTo('App\Models\Reservation', 'ReservationID', 'ReservationDetailID');
}
}
两个变形金刚的两个模型如下:
ReservationTransformer
public function transform(Reservation $reservation)
{
return [
'reservation_id' => (int) $reservation->ReservationID,
'reservation_no' => $reservation->ReservationNo,
];
}
ReservationDetail Transformer
public function transform(ReservationDetail $reservation_detail)
{
return [
'reservation_detail_id' => (int) $reservation_detail->ReservationDetailID,
'reservation_id' => (int) $reservation_detail->ReservationID,
'room_no' => $reservation_detail->RoomNo,
];
}
我的控制器并查询
$reservation = Reservation::where('ReservationNo', '=', $reservation_no)
->with('ReservationDetails')
->get();
return $reservation;
我得到以下回复
{
"Reservations": [
{
"ReservationID": "1",
"ReservationNo": "2016-06-01 16:50:59.0659",
"reservation_details": [
{
"ReservationDetailID": "1",
"ReservationID": "1",
"RoomNo": "001",
},
{
"ReservationDetailID": "2",
"ReservationID": "1",
"RoomNo": "002",
}
]
}
]
}
我尝试以下操作,但只返回主表的翻译。
$reservation = $this->collection($reservation, new ReservationTransformer());
**
如何将master和detail表的数据一起转换?
**
我真的不明白'自定义转换图层'是如何工作的,谁能给我一个例子?
非常感谢。
答案 0 :(得分:1)
您可以使用分形构建来支持变换器包含。见http://fractal.thephpleague.com/transformers/
我首先将public function hasManyReservationDetails()
重命名为public function reservationDetails()
。
然后您的ReservationTransformer将处理其余的事情:
use League\Fractal\TransformerAbstract;
class ReservationTransformer extends TransformerAbstract
{
/**
* List of resources to automatically include
*
* @var array
*/
protected $defaultIncludes = [
'reservationDetails',
];
public function transform(Reservation $reservation)
{
return [
'reservation_id' => (int) $reservation->ReservationID,
'reservation_no' => $reservation->ReservationNo,
];
}
/**
* Include ReservationDetail
*
* @param Reservation $reservation
*
* @return League\Fractal\Resource\Collection
*/
public function includeReservationDetails(Reservation $reservation)
{
return $this->collection($reservation->reservationDetails, new ReservationDetailTransformer);
}
}