whereHas, with,has的区别

  1. has语句执行的sql
SELECT
	*
FROM
	`gs_store_corner_marks`
WHERE
	EXISTS (
		SELECT
			*
		FROM
			`gs_store_goods`
		INNER JOIN `gs_store_goods_corner_marks` ON `gs_store_goods`.`id` = `gs_store_goods_corner_marks`.`goods_id`
		WHERE
			`gs_store_corner_marks`.`id` = `gs_store_goods_corner_marks`.`corner_mark_id`
		AND `gs_store_goods`.`deleted_at` IS NULL
	)
AND `store_id` = 1000106
ORDER BY
	`gs_store_corner_marks`.`id` DESC
  1. whereHas语句执行的sql
SELECT
	*
FROM
	`gs_store_corner_marks`
WHERE
	EXISTS (
		SELECT
			*
		FROM
			`gs_store_goods`
		INNER JOIN `gs_store_goods_corner_marks` ON `gs_store_goods`.`id` = `gs_store_goods_corner_marks`.`goods_id`
		WHERE
			`gs_store_corner_marks`.`id` = `gs_store_goods_corner_marks`.`corner_mark_id`
		AND `validity_type` = 2
		AND `gs_store_goods`.`deleted_at` IS NULL
	)
AND `store_id` = 1000106
ORDER BY
	`gs_store_corner_marks`.`id` DESC
  1. with执行的sql
SELECT
	*
FROM
	`gs_store_corner_marks`
WHERE
	`store_id` = 1000106
ORDER BY
	`gs_store_corner_marks`.`id` DESC

SELECT
	`gs_store_goods`.*, `gs_store_goods_corner_marks`.`corner_mark_id` AS `pivot_corner_mark_id`,
	`gs_store_goods_corner_marks`.`goods_id` AS `pivot_goods_id`
FROM
	`gs_store_goods`
INNER JOIN `gs_store_goods_corner_marks` ON `gs_store_goods`.`id` = `gs_store_goods_corner_marks`.`goods_id`
WHERE
	`gs_store_goods_corner_marks`.`corner_mark_id` IN (34, 39, 40, 41, 42, 48, 49, 50, 54)
AND `gs_store_goods`.`deleted_at` IS NULL

他们的示例:

$goods_lists = $this->cornerMark
            ->where(['validity_type'=>2])
            ->where('id', '<>', $param['id'])
            ->with('goods')
            ->whereHas('goods', function ($query) {
                return $query->where('store_goods.store_id', $this->storeId);
            })
            ->get()->toArray();

使用实例一:商品表,分类表,搜索商品分类

$list = Goods::whereIn('is_delete', [0, 2])
            ->when(!empty($params['category_id']), function ($query) use ($params) {
                $query->whereHas('goodsCateRelation', function ($query) use ($params) {
                    if (!empty($params['category_id'])) {
                        $query->where('category_id', $params['category_id']);
                    }
                });
            })

使用实例二:商品分为单规格,多规格,搜索规格值

$list = Goods::whereIn('is_delete', [0, 2])
	->when(!empty($params['entity_no']), function ($query) use ($params) {
                $query->where('entity_no', $params['entity_no'])->orWhereHas('goodsEntity', function ($query) use ($params) {
                    if (!empty($params['entity_no'])) {
                        $query->where('entity_no', $params['entity_no']);
                    }
                });
    })

你可能感兴趣的:(laravel)