I am trying to fetch all classes of Entry with some condition on it's attributes. One relationship, tags, should be eager loaded.
The models looks like so
class Tag extends Eloquent {
protected $table = 'tags';
protected $guarded = array();
public function entries()
{
return $this->belongsToMany('Entry');
}
}
class Entry extends Eloquent {
protected $table = 'entries';
protected $guarded = array();
public function tags()
{
return $this->belongsToMany('Tag');
}
public function user()
{
return $this->belongsTo('User');
}
public function votes()
{
return $this->hasMany('Votes');
}
}
Table entry_tag with dual foreign keys, entry_id,tag_id, exists.
I am trying to use this code. (1)
$testEntries = Entry::with(array('tags' => function($query)
{
$query->where('tag_id', '=', '1');
}))->get();
however, it returns nothing. even using the code below yields completely zilch. (2)
$testEntries = Entry::with('tags')->get();
Inspecting the DB log, I can see that the queries are OK. They yield (3)
select `tags`.*, `entry_tag`.`entry_id` as `pivot_entry_id`, `entry_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `entry_tag` on `tags`.`id` = `entry_tag`.`tag_id` where `entry_tag`.`entry_id` in (?, ?, ?, ?, ?, ?, ?, ?)","bindings":["1","2","3","4","5","6","7","8"]
and (4)
select `tags`.*, `entry_tag`.`entry_id` as `pivot_entry_id`, `entry_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `entry_tag` on `tags`.`id` = `entry_tag`.`tag_id` where `entry_tag`.`entry_id` in (?, ?, ?, ?, ?, ?, ?, ?) and `tag_id` = ?","bindings":["1","2","3","4","5","6","7","8","1"]
which both work (and finds results) when executing the queries manually.
What am I missing? I've scratched my head a few hours now!
EDIT:
I've tried displaying the results, without any luck, like below
Log::debug('testing fetching entries:: ' . json_encode($testEntries));
and
foreach(Entry::with('tags')->get() as $entry)
{
Log::debug('test1!! ' . json_encode($entry));
}
EDIT 2: I have tried fetching Tags with their entries, like so
Tag::with('entries')->get();
but it (along with other combinations) returns zero results every time. I am thinking maybe I have missed something fundamental in the way I have set up tables. Here is the complete sql output for attempt (2), in case it helps.
{"query":"select * from `entries`","bindings":[],"time":0.33},{"query":"select `tags`.*, `entry_tag`.`entry_id` as `pivot_entry_id`, `entry_tag`.`tag_id` as `pivot_tag_id` from `tags` inner join `entry_tag` on `tags`.`id` = `entry_tag`.`tag_id` where `entry_tag`.`entry_id` in (?, ?, ?, ?, ?, ?, ?, ?)","bindings":["1","2","3","4","5","6","7","8"],"time":0.74}