laravel 使用with和whereHas是不是没有直接使用join高效?
1. 问题描述?
/**
* 关联商家
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function merchant()
{
return $this->hasOne(Merchant::class, 'id', 'merchant_id');
}
/**
* 查询1
*/
public function list(array $param)
{
$obj = self::with(['merchant']);
return $obj->whereHas('merchant', function ($q) use ($param) {
if (isset($param['mobile'])) {
$q->where('mobile', $param['mobile']);
}
})->get();
}
/**
* 查询2
*/
public function list2(array $param)
{
return DB::table('user')->join('merchant as m','m.id', '=', 'u.merchant_id')
->where('m.mobile','=',$param['mobile'])->get();
}
with 是单独查询 whereHas 用的是exists join 是连表
whereHas 肯定慢 因为是全表扫描