数据库中有两个表,分别为一对多关系:主表(预约信息):dbo.Reservation [ReservationID] [INT] IDENTITY(1,1) NOT NULL, [ReservationNo] [NVARCHAR](24) NOT NULL, ......
明细表(预约明细):dbo.ReservationDetail [ReservationDetailID] [INT] IDENTITY(1,1) NOT NULL, [ReservationID] [INT] NOT NULL, --外键 ......
Model的代码如下:Reservation.php<?phpnamespace 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<?phpnamespace 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'); }
在一个API的controller里面调用<?phpnamespace App\\Api\\Controllers;use App\\Models\\Reservation;use App\\Models\\ReservationDetail;use App\\Http\\Requests;class ReservationController extends BaseController{ public function showByReservationNo($reservation\_no) { $reservation\_details = ReservationDetail::all() ->belongsToReservation() ->where('ReservationNo', '=', $reservation\_no) ->get(); return $reservation\_details; }
Laravel返回的错误信息如下: "message": "Method belongsToReservation does not exist.", "status\_code": 500,
请问这是什么原因,是不是namespace的问题?我希望实现的是用主表的某个条件关联去查询明细表,返回明细表的数据,查询的SQL语句如下:SELECT ReservationDetail.\*FROM ReservationDetailINNER JOIN Reservation ON Reservation.ReservationID = ReservationDetail.ReservationIDWHERE Reservation.ReservationNo = 'xxx'
请问各位大牛,问题出在什么地方?准确的语法应该怎么写?另一个问题是,如果希望返回的数据是将主表和明细表合并成一个对象返回,例如:{ "ReservationID": "1", "ReservationNo": "201601011000", "ReservationDetails": [ { "ReservationDetailID": "1", "ReservationID": "1", }, { "ReservationDetailID": "2", "ReservationID": "1", } ]}
关联查询应该怎么写?请各位大牛赐教,感激涕零!!!
修改的评论也不能少于六个字哦!
0
分享