Теперь мне нужно получить все бронирования пользователей, вошедших в систему, со статусом резервирования и его переводом. Вот структура моих моделей/таблиц:
Код: Выделить всё
class Place extends Model
{
use HasFactory, SoftDeletes;
public function users()
{
return $this->belongsToMany(User::class, 'reservations')
->withPivot(['id', 'reservation_number', 'reservation_status_id'])
->as('reservations')
->withTimestamps();
}
}
Код: Выделить всё
class User extends Authenticatable
{
use HasFactory, HasApiTokens, Notifiable, SoftDeletes, HasRoles;
public function places()
{
return $this->belongsToMany(Place::class, 'reservations')
->withPivot(['id', 'reservation_number', 'reservation_status_id'])
->as('reservations')
->withTimestamps();
}
}
Код: Выделить всё
class Reservation extends Pivot
{
use HasFactory, SoftDeletes;
protected $table = 'reservations';
protected $fillable = [
'user_id',
'place_id',
'reservation_status_id'
];
public function reservationStatus()
{
return $this->belongsTo(ReservationStatus::class);
}
}
Код: Выделить всё
class ReservationStatus extends Model
{
public function reservations()
{
return $this->hasMany(Reservation::class);
}
public function reservationStatusTranslations()
{
return $this->hasMany(ReservationStatusTranslation::class);
}
}
Код: Выделить всё
class ReservationStatusTranslation extends Model
{
use HasFactory;
protected $fillable = [
'name',
'reservation_status_id',
'language_id',
];
public function reservationStatus()
{
return $this->belongsTo(ReservationStatus::class);
}
public function language()
{
return $this->belongsTo(Language::class);
}
}
Код: Выделить всё
public function index()
{
$user = request()->user();
$reservations = $user->places()->get(['places.id', 'name']);
return $this->sendResponse(__('general.list_all_reservations'), $reservations);
}
Код: Выделить всё
{
"success": true,
"message": "List all reservations",
"data": [
{
"id": 1,
"name": "farm",
"reservations": {
"user_id": 151,
"place_id": 1,
"id": 122,
"reservation_number": "772-826-152",
"reservation_status_id": 4, // here I need the reservation status relationship and then access the reservation status translation relationship
"created_at": "2024-06-25T19:23:16.000000Z",
"updated_at": "2024-06-25T19:23:54.000000Z"
}
}
]
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... y-relation