SQLSTATE [42S22]: Column not found: 1054 Unknown column LARAVEL 5.4

2

I can not access the relationship with with from the parent table to the daughter, she says:

  

SQLSTATE [42S22]: Column not found: 1054 Unknown column   'subComidas.comida_id' in 'where clause' (SQL: select * from    subComidas where subComidas . comida_id in (1, 2))

The weird thing is that I check the models and they're fine. In fact, I can call the relationship from the daughter table without problems or other food relations.

Table model Meals

class comida extends Model
{
protected $table = 'comidas';

protected $fillable = [
    'id',
    'cm_nombre',
    'created_at',
    'us_id',
    'updated_at'
];

// SUS HIJOS
public function planesAlimentarios(){
    return $this->belongsToMany('frust\planesAlimentario');
}

public function alimentos(){
  return $this->belongsToMany('frust\alimento');
}

public function subComida(){
    return $this->hasMany('frust\subComida');
}

// SUS PADRES
public function User(){
    return $this->belongsTo('frust\User','us_id','id');
}
}

Taba daughter model:

class subComida extends Model

{
protected $table = 'subComidas';

protected $fillable = [
    'id',
    'sbc_nombre',
    'sbc_porcentaje',
    'created_at',
    'cm_id',
    'updated_at'
];
// SUS HIJOS
// SUS PADRES
    public function Comida(){
        return $this->belongsTo('frust\Comida','cm_id','id');
}
}

How I try to bring the objects from the parent table and I get an error:

$comidas = comida::with(['subComida'])->paginate(5);        
    dd($comidas);

How can I try to bring the objects from the daughter table (and bring them without problems)

$comidas = subComida::with(['Comida'])->paginate(5);        
    dd($comidas);

I also tried to overwrite the primary keys with $ primaryKey

Version of laravel: 5.4

    
asked by César Alejandro M 19.10.2017 в 06:00
source

2 answers

2

When you define the subComida relationship in the comida model, you can also specify the field of the foreign key as the second parameter, and the local key as the third parameter, in case these two do not follow the default schemas of Laravel, as is your case, specifically with the foreign key:

public function subComida(){
    return $this->hasMany('frust\subComida', 'cm_id');
}
    
answered by 19.10.2017 / 06:47
source
0

In the model of the specific child class, the name of the IDs is not what laravel expects by default but in the parent you do not specify it. Therefore try to perform the query with a field that does not exist.

Edit the parent model by specifying the correct name of the id column.

    
answered by 19.10.2017 в 06:24