我收到如下错误 在模型[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');
}
}
模型文件Room.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文件中可能存在错误。
答案 0 :(得分:0)
您的Hotel
课程中的hasMany定义不正确。
根据API文档here,您需要传递Room
类的实例。
public function room() {
return $this->hasMany(App\Room::class, 'hotel_id');
// OR
return $this->hasMany('App\Room', 'hotel_id');
}
同样适用于您的Room
课程。
public function hotel() {
return $this->belongsTo(App\Hotel::class, 'hotel_id');
// OR
return $this->belongsTo('App\Hotel', 'hotel_id');
}
- 编辑 -
在评论中,belongsTo
函数具有以下定义:
belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
要使hotel()
类上的Room
关系起作用,您需要将相关模型键作为第二个参数传递。你应该这样写:
public function hotel() {
return $this->belongsTo('App\Hotel', 'id', 'hotel_id');
}