Skip to content
Advertisement

Eloquent hasMany doesn’t load collection

I’m relatively new to eloquent, and have problems loading data from a hasMany relation in an app that uses eloquent as the database layer. My (simplified) code is as follows:

use IlluminateDatabaseEloquentModel;
class Answer extends Model{
    protected $table = 'answer';
    public $timestamps = false;
    public $incrementing = false;
    protected $fillable = [
        "nerdId",
        "invitationid",
        "eatingno",
        "price",
        "haspaid",
        "attending",
        "noeating",
    ];
    public function topping() {
        return $this->hasMany(AnswerTopping::class, 'answerid');
    }
}

class AnswerTopping extends Model{
    protected $table = 'eating';
    public $timestamps = false;
    protected $fillable = [
        'answerid',
        'toppingid',
        'add'
    ];

    public function answer() {
        return $this->belongsTo(Answer::class);
    }
}

The SQL Schema is like below

CREATE TABLE `answer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nerdid` int(11) NOT NULL,
  `invitationid` int(11) NOT NULL,
  `eatingno` tinytext,
  `price` float NOT NULL,
  `haspaid` tinyint(4) NOT NULL,
  `attending` tinyint(1) NOT NULL DEFAULT '0',
  `noeating` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2119 DEFAULT CHARSET=utf8;
CREATE TABLE `eating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `answerId` int(11) NOT NULL,
  `toppingid` int(11) NOT NULL,
  `add` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=280 DEFAULT CHARSET=utf8;

I then do the following query:

    $answer = Answer::with('topping')->find(32);
    return $answer->toJson());

This results in a json like the following

{"id":32,"nerdid":1,"invitationid":54,"eatingno":"51","price":60,"haspaid":1,"attending":2,"noeating":0,"topping":[]}

Raw SQL query shows me that I do have data in the relation, so it should return more in “topping”.

UPDATE Checking sql queries in mysql (Setting it up for logging), I see that it actually do the expected queries on the database:

select * from `answer` where `answer`.`id` = 32 limit 1;
select * from `eating` where `eating`.`answerid` in (32);

Manually executing the SQL are giving me 2 entries in the eating table. But they are not showing up on the upper “Answer” json.

Advertisement

Answer

Found the culprit.. db schema for the “eating” table, had answerId (uppercase I), and the relation in hasMany used answerid (lowercase i), which apparently confused eloquent..

Now I get the expected json..

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement