I can't access the relationship with with from the parent table to the child table, it tells me:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'subMeals.meal_id' in 'where clause' (SQL: select * from
subComidas
wheresubComidas
.comida_id
in (1, 2))
The strange thing is that I check the models and they are fine. In fact, I can call the relation from the child table with no problems or other food relations.
Meals table model
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');
}
}
Model was daughter:
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');
}
}
As I try to bring the objects from the parent table and it gives me an error:
$comidas = comida::with(['subComida'])->paginate(5);
dd($comidas);
How can I try to bring the objects from the child table (and it brings them without problems)
$comidas = subComida::with(['Comida'])->paginate(5);
dd($comidas);
I also tried to overwrite the primary keys with $primaryKey
Laravel version: 5.4
When you define the relationship
subComida
in the modelcomida
, you can also specify the foreign key field as the second parameter, and the local key as the third parameter, in case these two don't follow Laravel's default schemas, as you do, specifically with the foreign key:In the model of the child class, you specify that the name of the IDs is not the one that Laravel expects by default, but in the parent you do not specify it. Therefore, it tries to perform the query with a field that does not exist.
Edit the parent model specifying the correct id column name.