with 和 whereHas 的配合使用

Besny1009發表於2021-06-02

模型配置

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);
            }
        })
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章