Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

JOIN ... USING in CodeIgniter Active Record ergänzen

Die Active-Record-Klasse unterstützt JOIN ... USING nicht von Haus aus. Ihre Optionen: join() in system/database/DB_active_rec.php anpassen:

public function join($table, $cond, $type = '') { if ($type != '') { $type = strtoupper(trim($type)); if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'))) { $type = ''; } else { $type .= ' '; } } // Extract any aliases so _protect_identifiers knows to add a prefix $this->_track_aliases($table); // Protect the identifiers on both sides of the condition if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match)) { $match[1] = $this->_protect_identifiers($match[1]); $match[3] = $this->_protect_identifiers($match[3]); $cond = $match[1] . $match[2] . $match[3]; } $join = $type . 'JOIN ' . $this->_protect_identifiers($table, TRUE, NULL, FALSE); if (preg_match('/using[ (]/i', $cond)) { $join .= ' ' . $cond; } else { $join .= ' ON ' . $cond; } $this->ar_join[] = $join; if ($this->ar_caching === TRUE) { $this->ar_cache_join[] = $join; $this->ar_cache_exists[] = 'join'; } return $this; }

Danach können Sie join('table', 'USING ("something")') schreiben.

Kerndateien zu bearbeiten ist allerdings eine schlechte Idee – jedes Framework-Upgrade macht es rückgängig. Erweitern Sie stattdessen die Klasse; siehe Extending Database Drivers oder diese Anleitung.

Oder umgehen Sie die Erweiterung mit einem kleinen Helper:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); function join_using($table, $key) { $CI =& get_instance(); return $CI->db->ar_join[] = 'JOIN ' . $table . ' USING (`' . $key . '`)'; }

Helper laden und join_using('table', 'key') aufrufen. Zum Beispiel:

// these two produce the same result $something1 = $this->db->join('join_table', 'join_table.id = table.id') ->get('table')->result(); print_r($something1); join_using('join_table', 'id'); $something2 = $this->db->get('table')->result(); print_r($something2);

Zwei Korrekturen am Original-Snippet: get_instance() sollte im PHP-5-Codebase von CI3 per Referenz zugewiesen werden (=&), und $join war in der gezeigten Core-Version vor .= nie deklariert. Außerdem wurde Active Record in CI3.1 zu Query Builder umbenannt und in CI4 komplett entfernt – auf CI4 gilt dieser Ansatz also nicht mehr. Bauen Sie das SQL dort mit join() des Query Builders und einer expliziten ON-Klausel.