【发布时间】:2013-10-22 04:24:50
【问题描述】:
我正在尝试获取所有类别的条目,并对其属性进行一些条件。一种关系,标签,应该是预先加载的。
模型看起来像这样
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_id,tag_id 的表 entry_tag。
我正在尝试使用此代码。 (1)
$testEntries = Entry::with(array('tags' => function($query)
{
$query->where('tag_id', '=', '1');
}))->get();
但是,它什么也不返回。 即使使用下面的代码也会完全产生 zilch。 (2)
$testEntries = Entry::with('tags')->get();
检查数据库日志,我可以看到查询正常。他们产生 (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();
但它(连同其他组合)每次都返回零结果。我在想也许我在设置表格的方式上错过了一些基本的东西。以下是尝试 (2) 的完整 sql 输出,以防万一。
{"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');,反之亦然 -
您如何尝试显示结果?也许某处有错字。
-
@GladToHelp,没有变化。由于它当前创建了成功的 sql 查询(查看数据库日志),因此没有区别是有道理的。
-
@user1669496 我在问题中添加了信息。
-
@C-A 当您尝试获取单个条目而不进行过滤或急切加载时,它是否有效?
$testEntries = Entry::find(1);之类的东西?
标签: php mysql laravel eloquent eager-loading