0

我正在尝试获取所有类别的条目,并对其属性有一些条件。一种关系,标签,应该是预先加载的。

模型看起来像这样

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}
4

1 回答 1

0

如果您使用软删除特征,则检查deleted_at具有默认值NULL

于 2016-09-12T12:35:11.577 回答