php - Laravel 多对多急切加载总是返回空结果

标签 php mysql laravel eloquent eager-loading

我正在尝试获取所有具有某些属性条件的 Entry 类。应该立即加载一种关系(标签)。

模型看起来像这样

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();

但是,它什么也没返回。 即使使用下面的代码也完全没有效果。 (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();

但它(以及其他组合)每次都返回零结果。我想也许我在设置 table 的方式上错过了一些基本的东西。这是尝试 (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}

最佳答案

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

关于php - Laravel 多对多急切加载总是返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19508938/

相关文章:

javascript - 运行 javascript 函数而不是从 Laravel 发布表单

php - Codeigniter 删除连接子句中的 "("

Mysql 选择 4 个连接表的值

MySQL连续几天进行分组和聚合

php - Laravel Eloquent - 检查返回的对象是否有效

php - 使用 Laravel 4 的 Intervention\Image\Exception\NotWritableException

PHP 将 800 条记录从数据库写入文件 (.txt)

javascript - 提交页面时使用ajax保留选中的复选框

javascript - PHP - 无法正确发送 JSON

java - 使用 JavaMail 在超过截止日期时自动向用户发送电子邮件