Thursday, February 15, 2018

Hierarchical data in MySQL: parents and children in one query

The idea is, how to implement a hierarchical query in MySQL (using the ancestry chains version) for a single row, such that it picks up the parents (if any) and any children (if any).

We need to combine two queries here:
  1. Original hierarchical query that returns all descendants of a given id (a descendancy chain)
  2. A query that would return all ancestors of a given id (an ancestry chain)
An id can have only one parent, that's why we can employ a linked list technique to build an ancestry chain, like shown in this article:

Here's the query to to this (no functions required):


SELECT  CONCAT(REPEAT('    ', level  - 1), _id) AS treeitem, parent, level
FROM    (
        SELECT  @r AS _id,
                (
                SELECT  @r := parent
                FROM    t_hierarchy
                WHERE   id = _id
                ) AS parent,
                @l := @l + 1 AS level
        FROM    (
                SELECT  @r := 1218,
                        @l := 0,
                        @cl := 0
                ) vars,
                t_hierarchy h
        WHERE   @r <> 0
        ORDER BY
                level DESC
        ) qi

Click to see more details. Thanks to Quassnoi to made my day easy!!  

Tuesday, October 24, 2017

laravel 5 - Properly handle TokenMismatchException

In laravel 5 , When the token is expired you could get the TokenMismatchException. So we can avoid the exception and redirect back to the page with some error notification messages is best for the users.

I searched around and could not find a 100% definitive solution to this. I was able to find this bit of code but it does not seem to make any difference: App\Exceptions\Handler.php

 
public function render($request, Exception $exception){ 
  if ($exception instanceof TokenMismatchException){ 
    return redirect(url()->previous())->with('alert-danger', 
"Oops! Seems you couldn't submit form for a long time. 
Please try again."); 
    }
    return parent::render($request, $exception); 
 }