Compound primary key: Illegal offset type error in laravel 5

1

I am new to Laravel and I do not know how to solve this problem, which is as follows:

I have a table like that on MySql:

Table: propiedad_x_tipo
Columns:
**id_tipo_propiedad** int(11) **PK** 
**id_propiedad** int(11) **PK**

As you can see the two columns are primary keys.

Now my model is as follows:

class Tipo_X_Propiedad extends Model
{
    protected $table='propiedad_x_tipo';
    protected $primaryKey= ['id_tipo_propiedad','id_propiedad'];
    public $timestamps=false;
    protected $fillable=[
        'id_tipo_propiedad',
        'id_propiedad'
    ];
    protected $guarded=[

    ];
}

and when inserting into the database I do it like this:

$tipos_seleccionados=$request->get('tipo_propiedad');

        foreach ($tipos_seleccionados as $key => $value ) {
            $tipo_x_propiedad=new Tipo_X_Propiedad;
            $tipo_x_propiedad->id_tipo_propiedad=$key.$value;
            $tipo_x_propiedad->id_propiedad=(int)$count;
            $tipo_x_propiedad->save();

        }

But it gives me an error when running it:

  

(1/1) ErrorException       Illegal offset type       in HasAttributes.php (line 820)       at HandleExceptions-> handleError (2, 'Illegal offset type', 'C: \ Users \ USER \ Documents \ XXXX \ XXXX \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Eloquent \ Concerns \ HasAttributes.php', 820, array ())       in HasAttributes.php (line 820)

    
asked by Brayan Chavarria 22.09.2017 в 01:41
source

1 answer

1

Basically Eloquent NO supports primary primary keys. You can see more information (in English) at the following link: link

Also, in the file that the models Illuminate/Database/Eloquent/Model.php extend, you can see that Eloquent / Laravel expects a string in the value of $ primaryKey and that is probably the cause of your error, then the code that I mention to you:

abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{

    // ...

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    // ...
    
answered by 23.09.2017 в 03:47