PHP динамическое разбиение на страницы без SQL

Быстрый Ответ : при замене использования leftJoin только с соединением (или innerJoin) тогда, Вы получите то, что Вы хотите: только Сообщения, которые имеют по крайней мере 1 фотографию.

Детали

, Если Вы смотрите на это полезное ТАК Q& A:

Методы Соединения MySQL Different

... Вы найдете некоторые превосходные схемы Венна, показывающие различие между левым и внутренним объединением. Затем при изучении класса Доктрины Doctrine\ORM\QueryBuilder Вы найдете, что у них есть три метода соединения:

  • соединение (который просто называет innerJoin)
  • innerJoin
  • leftJoin
    /**
     * Creates and adds a join over an entity association to the query.
     *
     * The entities in the joined association will be fetched as part of the query
     * result if the alias used for the joined association is placed in the select
     * expressions.
     *
     * 
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->join('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
     * 
     *
     * @param string      $join          The relationship to join.
     * @param string      $alias         The alias of the join.
     * @param string|null $conditionType The condition type constant. Either ON or WITH.
     * @param string|null $condition     The condition for the join.
     * @param string|null $indexBy       The index for the join.
     *
     * @return self
     */
    public function join($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
    {
        return $this->innerJoin($join, $alias, $conditionType, $condition, $indexBy);
    }

    /**
     * Creates and adds a join over an entity association to the query.
     *
     * The entities in the joined association will be fetched as part of the query
     * result if the alias used for the joined association is placed in the select
     * expressions.
     *
     *     [php]
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->innerJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
     *
     * @param string      $join          The relationship to join.
     * @param string      $alias         The alias of the join.
     * @param string|null $conditionType The condition type constant. Either ON or WITH.
     * @param string|null $condition     The condition for the join.
     * @param string|null $indexBy       The index for the join.
     *
     * @return self
     */
    public function innerJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
    {
        $parentAlias = substr($join, 0, strpos($join, '.'));

        $rootAlias = $this->findRootAlias($alias, $parentAlias);

        $join = new Expr\Join(
            Expr\Join::INNER_JOIN, $join, $alias, $conditionType, $condition, $indexBy
        );

        return $this->add('join', [$rootAlias => $join], true);
    }

    /**
     * Creates and adds a left join over an entity association to the query.
     *
     * The entities in the joined association will be fetched as part of the query
     * result if the alias used for the joined association is placed in the select
     * expressions.
     *
     * 
     *     $qb = $em->createQueryBuilder()
     *         ->select('u')
     *         ->from('User', 'u')
     *         ->leftJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
     * 
     *
     * @param string      $join          The relationship to join.
     * @param string      $alias         The alias of the join.
     * @param string|null $conditionType The condition type constant. Either ON or WITH.
     * @param string|null $condition     The condition for the join.
     * @param string|null $indexBy       The index for the join.
     *
     * @return self
     */
    public function leftJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
    {
        $parentAlias = substr($join, 0, strpos($join, '.'));

        $rootAlias = $this->findRootAlias($alias, $parentAlias);

        $join = new Expr\Join(
            Expr\Join::LEFT_JOIN, $join, $alias, $conditionType, $condition, $indexBy
        );

        return $this->add('join', [$rootAlias => $join], true);
    }


, Изменяющий Ваш код, чтобы использовать innerJoin (или просто присоединиться), приведет Доктрину выпускать ВНУТРЕННЕЕ ОБЪЕДИНЕНИЕ в сгенерированном SQL, который возвратит только записи, где "что-то" существует с обеих сторон соединения, таким образом любое Сообщение, которое не имеет никаких фотографий, не будет включено в результаты.

7
задан PHLAK 16 October 2008 в 02:24
поделиться

4 ответа

разбиение на страницы является тем же понятием с, или без sql. Вам просто нужны Ваши основные переменные, затем можно создать содержание, которое Вы хотите. вот некоторый квазикод:

$itemsPerPage = 5;

$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$totalItems = getTotalItems();
$totalPages = ceil($totalItems / $itemsPerPage);

function getTotalItems() {
// since they're images, perhaps we'll scan a directory of images to determine
// how many images we have in total
}

function getItemsFromPage($page, $itemsPerPage) {
// function to grab $itemsPerPage based on which $page we're on
}

function getPager($totalPages, $currentPage) {
// build your pager
}

надежда, которая помогает Вам начать!

9
ответ дан 6 December 2019 в 10:04
поделиться

Это - функция, которую я часто использую, чтобы сделать разбиение на страницы. Надежда это помогает.

function paginate($page, $total, $per_page) {
    if(!is_numeric($page)) { $page = 1; }
    if(!is_numeric($per_page)) { $per_page = 10; }
    if($page > ceil($total / $per_page)) $page = 1;
    if($page == "" || $page == 0) { 
        $page = 1;
        $start = 0;
        $end = $per_page;
    } else {
        $start = ($page * $per_page) - ($per_page);
        $end = $per_page;
    }

    $prev_page = "";
    $next_page = "";
    $all_pages = array();
    $selected = "";
    $enabled = false;

    if($total > $per_page) {
        $enabled = true;
        $prev = $page - 1;
        $prev_page = ($prev == 0) ? 0 : $prev;

        $next = $page + 1;
        $total_pages = ceil($total/$per_page);

        $next_page = ($next <= $total_pages) ? $next : 0;

        for($x=1;$x<=$total_pages;$x++) {
            $all_pages[] = $x;
            $selected = ($x == $page) ? $x : $selected; 
        }
    }

    return array(
        "per_page" => $per_page,
        "page" => $page,
        "prev_page" => $prev_page,
        "all_pages" => $all_pages,
        "next_page" => $next_page,
        "selected" => $selected,
        "start" => $start,
        "end" => $end,
        "enabled" => $enabled
    );
}

// ex: we are in page 2, we have 50 items, and we're showing 10 per page
print_r(paginate(2, 50, 10));

Это возвратится:

Array
(
    [per_page] => 10
    [page] => 2
    [prev_page] => 1
    [all_pages] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )
    [next_page] => 3
    [selected] => 2
    [start] => 10
    [end] => 10
    [enabled] => 1
)

Со всеми этими данными Вы затем вполне прилично вооружены для создания ссылок разбиения на страницы.

10
ответ дан 6 December 2019 в 10:04
поделиться

При именовании изображений 01.jpg 02.jpg, это помогает нумеровать страницы. Затем используйте шарик, чтобы получить все изображения в массив и отсортировать его.

0
ответ дан 6 December 2019 в 10:04
поделиться

Когда в сомнении используют JavaScript! Это могло бы помочь также: http://www.webplicity.net/flexigrid/

Могло бы быть хорошо для подобных galery приложений, хотя я никогда не пробовал его :)

0
ответ дан 6 December 2019 в 10:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: