2013-07-04 11 views
13

Quando voglio aggiornare il database FaqTrans, ma questo datase ha due chiavi primarie (faq_ida e lang) $table->primary(array('lang', 'faq_id'));. quindi non ho bisogno di una colonna id con auto_increment.Come aggiornare i dati con Eloquent senza id in Laravel 4

Tuttavia, quando utilizzo il seguente codice per aggiornare il database, il messaggio di errore mi indica che non esiste una colonna id.

$faq_trans = FaqTrans::where('faq_id','=',$faq_id)->where('lang','=',$lang)->first(); 
$faq_trans->lang = Input::get('lang'); 
$faq_trans->body = Input::get('body'); 
$faq_trans->title = Input::get('title'); 
$faq_trans->save(); 

messaggio di errore

SQLSTATE [42S22]: Colonna non trovata: 1.054 Unknown colonna 'id' in 'dove la clausola' (SQL: update FAQtrans impostato body =, updated_at = dove? id è nullo) (Binding: array (0 => 'adfadaaadfadaa', 1 => '2013/07/04 11:12:42',))

e quando ho aggiunto un Colonna id, il codice funziona bene ...

c'è un modo per aggiornare il database senza colonna ID?

+0

Si è impostata la chiave primaria nel modello –

+0

ho cercato di impostare la chiave primaria nel modello, ma sembra non può impostare due chiave primaria in una sola volta (chiave composita), come 'protetta $ primaryKey = array ('lang''faq_id'); ' –

+0

Potrebbe essere necessario usare' -> update (array ('column' => 'value')) 'invece di usare save. –

risposta

7

Laravel/Eloquent non supporta chiavi primarie composite.

Quando si controlla la classe Modello Eloquent, è possibile vedere che la chiave primaria può essere solo una stringa, utilizzata per creare la clausola WHERE.

1

Vai al tuo modello FaqTrans e aggiungi questo.

public $key = 'faq_id'; 

che dovrebbe farlo, assumendo faq_id è più importante che la lang

+0

Penso che ora sia $ primaryKey in base a questo: http://laravel.com/docs/eloquent # basic-usage – ftrotter

27

Scrivi questa linea nel vostro modello

public $primaryKey = '_id';

Dove _id è il manuale della chiave primaria

4

Abbastanza semplice:

6

Per chi si imbatte in questa domanda in futuro (come ho fatto io), ecco una soluzione alternativa per una chiave primaria composita in Eloquent.

questo va in cima alla vostra classe del modello:

protected $primaryKey = array('key1', 'key2'); 

Poi si ignorare il metodo save() del modello con questo:

public function save(array $options = array()) 
{ 
    if(!is_array($this->getKeyName())) 
     return parent::save($options); 

    // Fire Event for others to hook 
    if($this->fireModelEvent('saving') === false) 
     return false; 

    // Prepare query for inserting or updating 
    $query = $this->newQueryWithoutScopes(); 

    // Perform Update 
    if ($this->exists) { 
     if (count($this->getDirty()) > 0) { 
      // Fire Event for others to hook 
      if ($this->fireModelEvent('updating') === false) 
       return false; 

      // Touch the timestamps 
      if ($this->timestamps) 
       $this->updateTimestamps(); 

      // 
      // START FIX 
      // 

      // Convert primary key into an array if it's a single value 
      $primary = (count($this->getKeyName()) > 1) ? $this->getKeyName() : [$this->getKeyName()]; 

      // Fetch the primary key(s) values before any changes 
      $unique = array_intersect_key($this->original, array_flip($primary)); 

      // Fetch the primary key(s) values after any changes 
      $unique = !empty($unique) ? $unique : array_intersect_key($this->getAttributes(), array_flip($primary)); 

      // Fetch the element of the array if the array contains only a single element 
      $unique = (count($unique) <> 1) ? $unique : reset($unique); 

      // Apply SQL logic 
      $query->where($unique); 

      // 
      // END FIX 
      // 

      // Update the records 
      $query->update($this->getDirty()); 

      // Fire an event for hooking into 
      $this->fireModelEvent('updated', false); 
     } 

    // Perform Insert 
    } else { 
     // Fire an event for hooking into 
     if ($this->fireModelEvent('creating') === false) 
      return false; 

     // Touch the timestamps 
     if ($this->timestamps) 
      $this->updateTimestamps(); 

     // Retrieve the attributes 
     $attributes = $this->attributes; 

     if ($this->incrementing && !is_array($this->getKeyName())) 
      $this->insertAndSetId($query, $attributes); 
     else 
      $query->insert($attributes); 

     // Set exists to true in case someone tries to update it during an event 
     $this->exists = true; 

     // Fire an event for hooking into 
     $this->fireModelEvent('created', false); 
    } 

    // Fires an event 
    $this->fireModelEvent('saved', false); 

    // Sync 
    $this->original = $this->attributes; 

    // Touches all relations 
    if (array_get($options, 'touch', true)) 
     $this->touchOwners(); 

    return true; 
} 

Fonte originale: https://github.com/laravel/framework/issues/5517#issuecomment-52996610

Aggiornamento 2016-05-03

Il mio nuovo modo preferito per fare questo:

How I can put composite keys in models in Laravel 5?

-1

Se qualcuno ha lo stesso problema. Ho usato la risposta Nishchit Dhanani e ha funzionato abbastanza bene che era: Scrivi questa riga nel tuo modello
public $ primaryKey = '_id';
Dove _id è la chiave primaria manuale

Per il mio caso. Ho avuto una tabella utenti e parte dei miei utenti sono studenti. Quindi la chiave primaria nella tabella dei miei studenti era "user_id".
Aggiunta di questa linea nel mio modello Studente: public $ primaryKey = 'user_id';

Sono stato in grado di utilizzare il metodo save() durante l'aggiornamento del mio oggetto studente.

Spero che questo aiuti

+1

Rispondi solo alle risposte che ritieni utili, piuttosto che scrivere altre risposte per ripeterle. –

Problemi correlati