with 和 whereHas 的配合使用

Laravel框架
395
0
0
2022-04-19

模型配置

class MarketWork extends Model
{
    protected $table = 'market_work';
    public $timestamps = false;

    // public function send_log(){ 
    //     return $this->belongsTo(SendLog::class, 'id', 'work_id'); 
    // } 
    public function project(){
        return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id','is_del','is_public','number']);
    }
    public function user(){
        return $this->belongsTo(User::class, 'user_id', 'id')->where('is_del',0)
        ->select(['id','account','full_name','agent_id']);
    }


}

控制器实现逻辑

$list = $work->with(['user'=>function($query){
            $query->with(['agent'=>function($query){
                $query->with(['pagent']);
            }]);
        },'project:id,is_del,is_public'])
        ->whereHas('user',function($query) use($account,$full_name){
            if(!empty($account)){
                $query->where('account','like','%'.$account.'%');
            }
            if(!empty($full_name)){
                $query->where('full_name','like','%'.$full_name.'%');
            }
        })
        ->whereHas('project',function($query) use($is_public){
            if(!empty($is_public)){
                $query->where('is_public',1);
            }
        })
        ->whereHas('user.agent',function($query) use($agent_id){
            if(!empty($agent_id)){
                $query->where('id',$agent_id)->orWhere('pid',$agent_id);
            }
        })