0
我想获取所有类的条目,其中有一些条件属性。一个关系,标签,应该急切加载。Laravel多对多急切加载总是返回空结果
的模型看起来像双外键,entry_id,TAG_ID所以
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');
}
}
表entry_tag,存在。
我正尝试使用此代码。 (1)
$testEntries = Entry::with(array('tags' => function($query)
{
$query->where('tag_id', '=', '1');
}))->get();
但是,它没有返回。 即使使用下面的代码也会产生完全的zilch。 (2)
$testEntries = Entry::with('tags')->get();
检查数据库日志,我可以看到,查询都OK。它们产生 (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"]
和 手动执行查询时(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"]
其中两个工作(并且发现结果)。
我错过了什么?我现在几个小时就挠了脑袋!
编辑:
我已经试过显示结果,没有任何运气,像下面
Log::debug('testing fetching entries:: ' . json_encode($testEntries));
和
foreach(Entry::with('tags')->get() as $entry)
{
Log::debug('test1!! ' . json_encode($entry));
}
编辑2: 我曾尝试用他们的条目获取标签,如
Tag::with('entries')->get();
但它(连同其他组合)每次都返回零结果。我想也许我已经错过了我设置牌桌的方式。这里是完整的sql输出尝试(2),以防万一。
{"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}
不确定这是否有帮助,但尝试定义您的BelongsToMany()关系,如下所示:'return $ this-> belongsToMany('Entry','entry_tag','entry_id','tag_id');'and vice在Entry表中输入 –
你如何试图显示结果?也许在那里有一个错字。 – user1669496
@GladToHelp,没有变化。由于它目前创建了成功的SQL查询(查看数据库日志),所以没有什么区别。 –