How to Associate a Superclave in a Model in Laravel 5.6

0

I need to be able to create a Model in Laravel that allows the use of Superclaves to work with a table:

  <?php

  namespace app;

  use Illuminate\Database\Eloquent\Model;

  class Dpsector extends Model
  {
   protected $table='dpalmacen';

   protected $primaryKey="ALM_CODSUC,ALM_CODIGO";

   public $timestamps=false;

   protected $fillable =[
       'ALM_CODSUC',
       'ALM_CODIGO',
       'ALM_DESCRI',
       'ALM_A_E',
       'ALM_A_S',
       'ALM_T_E',
       'ALM_T_S',
       'ALM_DIR1',
       'ALM_DIR2',
       'ALM_ENCARG',
       'ALM_CODARE',
       'ALM_TEL1',
       'ALM_TEL2',
       'ALM_TEL3',
       'ALM_CODSUC',
       'ALM_ACTIVO',
       'ALM_P_E',
       'ALM_P_S',
       'ALM_CODTRA',
   ];

   protected $guarded =[

   ];
   /* EJEMPLO
    ALM_CODSUC ALM_CODIGO
    000001     0001
    000001     0002
    000001     0003
    000002     0001 
    000002     0002
   */
   }

As an achievement that laravel allows me to use more than one primary key in the model.

    
asked by Gregory Castellanos 06.11.2018 в 22:39
source

1 answer

0

Use more than one primary key if possible but you have to overwrite some methods of your Model class:

/**
 * Set the keys for a save update query.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
protected function setKeysForSaveQuery(Builder $query)
{
    $keys = $this->getKeyName();
    if(!is_array($keys)){
        return parent::setKeysForSaveQuery($query);
    }

    foreach($keys as $keyName){
        $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
    }

    return $query;
}

/**
 * Get the primary key value for a save query.
 *
 * @param mixed $keyName
 * @return mixed
 */
protected function getKeyForSaveQuery($keyName = null)
{
    if(is_null($keyName)){
        $keyName = $this->getKeyName();
    }

    if (isset($this->original[$keyName])) {
        return $this->original[$keyName];
    }

    return $this->getAttribute($keyName);
}

In your class attributes:

protected $primaryKey = ['primary_one', 'primary_two'];

// Supongo que ya no auto incrementarás, entonces debes de setear a falso el siguiente atributo:

public $incrementing = false;
    
answered by 07.11.2018 / 23:50
source