尝试在 Laravel 中读取 bool 上的 属性 id
Attempt to read property id on bool in Laravel
我尝试在 if 条件下为变量赋值
if ($hotel = Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()) {
if ($hotel->room_id == $room->id) {
return true;
}
}
我收到这个错误
Attempt to read property "room_id" on bool
同时 $hotel 变量不是布尔值
您的代码可以被编译器处理为
if ( $hotel = (
Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()
)
) {
//...
}
在这种情况下,您可以看到 $hotel 是 &&
运算符的布尔结果。
你应该添加括号来解决这个问题
if (
($hotel = Hotel::whereCode($this->hotelCode)->first()) &&
($room = Room::whereRoomCode($value)->first())
) {
if ($hotel->room_id == $room->id) {
return true;
}
}
或更明确的方式
$hotel = Hotel::whereCode($this->hotelCode)->first();
$room = Room::whereRoomCode($value)->first();
return $hotel && $room && ($hotel->room_id == $room->id);
或者使用关系并使用性能较低的方式(仅使用计数查询)
public function hasRoomByRoomCode($value)
{
return $this->room()->whereRoomCode($value)->count();
}
//this is the relation function if you did not set it yet inside Hotel::class
public function room()
{
return $this->belongsTo(Room::class);
}
我尝试在 if 条件下为变量赋值
if ($hotel = Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()) {
if ($hotel->room_id == $room->id) {
return true;
}
}
我收到这个错误
Attempt to read property "room_id" on bool
同时 $hotel 变量不是布尔值
您的代码可以被编译器处理为
if ( $hotel = (
Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()
)
) {
//...
}
在这种情况下,您可以看到 $hotel 是 &&
运算符的布尔结果。
你应该添加括号来解决这个问题
if (
($hotel = Hotel::whereCode($this->hotelCode)->first()) &&
($room = Room::whereRoomCode($value)->first())
) {
if ($hotel->room_id == $room->id) {
return true;
}
}
或更明确的方式
$hotel = Hotel::whereCode($this->hotelCode)->first();
$room = Room::whereRoomCode($value)->first();
return $hotel && $room && ($hotel->room_id == $room->id);
或者使用关系并使用性能较低的方式(仅使用计数查询)
public function hasRoomByRoomCode($value)
{
return $this->room()->whereRoomCode($value)->count();
}
//this is the relation function if you did not set it yet inside Hotel::class
public function room()
{
return $this->belongsTo(Room::class);
}