在雄辩的情况下为多表写入或写入

问题描述 投票:3回答:2

我使用eloquent作为ORM,我想在多表中使用where,如下所示:

$raw_query = EntityCity::with(['province']);
        $raw_query = $raw_query->where(function ( $q ) use ( $search_data ) {
            $q->where('city.title' , 'like' , "%$search_data%")
            ->orwhere('province.title' , 'like' , "%$search_data%");
        });
    }
    $this->data[ 'result_list' ] = $raw_query->limit($this->per_page)
                                             ->orderByDesc("time_insert")
                                             ->offset(( $page_num - 1 ) * $this->per_page)
                                             ->get();

但是,我遇到以下错误:

消息:SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'province.title'(SQL:从city中选择count(*)作为聚合(city.title喜欢%fars%或province.title like %尔斯%))

如果我评论orwhere它的工作原理。

那你怎么用orwhere写这个呢?

laravel laravel-5 eloquent
2个回答
2
投票

代替:

   $raw_query = $raw_query->where(function ( $q ) use ( $search_data ) {
        $q->where('city.title' , 'like' , "%$search_data%")
        ->orwhere('province.title' , 'like' , "%$search_data%");
    });
}

你应该使用:

$raw_query = $raw_query->where(function($q) {
     $q->where('city.title', 'like', "%$search_data%")
       ->orWhereHas('province', function ( $q ) use ( $search_data ) {
           $q->where('province.title' , 'like' , "%$search_data%");
      });
});

请注意,where ..或WhereHas被包装在其他where中,这使您有信心可以添加任何其他条件,例如仅选择活动城市:

$raw_query = $raw_query->where(function($q) {
     $q->where('city.title', 'like', "%$search_data%")
       ->orWhereHas('province', function ( $q ) use ( $search_data ) {
           $q->where('province.title' , 'like' , "%$search_data%");
      });
})->where('active', 1);   

1
投票

尝试使用orWhereHas

$raw_query = $raw_query->where('city.title', 'like', "%$search_data%")
        ->orWhereHas('province', function ( $q ) use ( $search_data ) {
            $q->where('province.title' , 'like' , "%$search_data%");
        });
© www.soinside.com 2019 - 2024. All rights reserved.