我收到如下错误调用模型 [App\Room] 上的未定义关系 [hotel_id]
模型文件 Hotel.php
class Hotel extends Model {
protected $primaryKey = 'id';
protected $fillable = ['hotel_name', 'hotel_area'];
public function room() {
return $this->hasMany('App\Room', 'hotel_id');
}
}
模型档案室.php
class Room extends Model {
protected $primaryKey = 'id';
protected $fillable = ['hotel_id', 'room_name', 'bonus_sum'];
public function hotel() {
return $this->belongsTo('App\Hotel', 'hotel_id');
}
}
控制器文件 RoomController.php
public function apiRoom() {
$rooms = Room::with('hotel');
return Datatables::eloquent($rooms)
->addColumn('action', function ($rooms) {
return '<a onclick="editForm('.$rooms->id.')" data-toggle="tooltip" data-original-title="Edit"> <i class="fa fa-pencil text-inverse m-r-10"></i> </a>'.
'<a onclick="deleteData('.$rooms->id.')" data-toggle="tooltip" data-original-title="Close"> <i class="fa fa-close text-danger"></i> </a>';
})
->escapeColumns()
->toJson();
路由文件 web.php
Route::get('rooms-list', 'RoomController@list');
Route::resource('room', 'RoomController', [
'except' => ['create']
]);
Route::get('api/room', 'RoomController@apiRoom')->name('api.room');
迁移 create_new_room
$table->increments('id');
$table->integer('hotel_id')->unsigned();
$table->foreign('hotel_id')->references('id')->on('hotels')->onDelete('cascade');
$table->string('room_name');
$table->string('bonus_sum');
$table->timestamps();
查看文件
$('#room-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('api.room') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'hotel.hotel_name', name: 'hotel.hotel_name'},
{data: 'room_name', name: 'room_name'},
{data: 'bonus_sum', name: 'bonus_sum'},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
它与数据库无关。ajax 文件中可能有错误。