Mysql
 sql >> Database >  >> RDS >> Mysql

Modello di Laravel con POINT/POLYGON ecc. utilizzando espressioni DB::raw

Ora abbiamo risolto questo problema genericamente per tutti i modelli estendendo il nostro modello base con la seguente funzionalità:

  • Definiamo un array di attributi che contengono dati geometrici.
  • Decidiamo in base al modello se vogliamo che questo venga caricato automaticamente come testo.
  • Modifichiamo il generatore di query predefinito per selezionare gli attributi della geometria come testo dal database.

Ecco un estratto dal modello base che ora utilizziamo:

/**
 * The attributes that hold geometrical data.
 *
 * @var array
 */
protected $geometry = array();

/**
 * Select geometrical attributes as text from database.
 *
 * @var bool
 */
protected $geometryAsText = false;

/**
 * Get a new query builder for the model's table.
 * Manipulate in case we need to convert geometrical fields to text.
 *
 * @param  bool  $excludeDeleted
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function newQuery($excludeDeleted = true)
{
    if (!empty($this->geometry) && $this->geometryAsText === true)
    {
        $raw = '';
        foreach ($this->geometry as $column)
        {
            $raw .= 'AsText(`' . $this->table . '`.`' . $column . '`) as `' . $column . '`, ';
        }
        $raw = substr($raw, 0, -2);
        return parent::newQuery($excludeDeleted)->addSelect('*', DB::raw($raw));
    }
    return parent::newQuery($excludeDeleted);
}