Laravel哪里有实体模型,哪里有相关的模态不起作用

时间:2018-02-15 07:48:40

标签: php mysql laravel laravel-5.5

我有三张桌子:

交易模式:

class Deal extends Model
{
    protected $guarded = ['id'];

    public function hotel() {
        return $this->belongsTo('App\Hotel');
    }
}

酒店型号:

class Hotel extends Model
{
    public function room(){
        return $this->hasMany('App\Room');
    }

    public function deal(){
        return $this->hasMany('App\Deal');
    }
}

会议室型号:

class Room extends Model
{

    public function hotel(){
        return $this->belongsTo('App\Hotel');
    }

}

以下查询正常,

return $greatDeals = Deal::whereHas('hotel', function ($query) {
                $query->Where('astatus', 1)->Where('status', 0);
            })->get();

但我想查询“酒店”模型,其中有“房间”模型 但是下面的查询显示错误,这个查询格式是否正确?

 return $greatDeals = Deal::whereHas('hotel', function ($query) {
                    $query->whereHas('room', function ($query) {
                        $query->Where('astatus', 1)->Where('status', 0);
                    })->get();
                })->get();

错误:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'deals.hotel_id' in 'where clause' (SQL: select * from `hotels` where `deals`.`hotel_id` = `hotels`.`id` and exists (select * from `rooms` where `hotels`.`id` = `rooms`.`hotel_id` and `astatus` = 1 and `status` = 0)) ◀"

1 个答案:

答案 0 :(得分:3)

删除第一个get()

Deal::whereHas('hotel', function ($query) {
        $query->whereHas('room', function ($query) {
            $query->where('astatus', 1)->where('status', 0);
        });
    })->get();

或者这样做:

Deal::whereHas('hotel.room', function ($query) {
        $query->where('astatus', 1)->where('status', 0);
    })->get();