【问题标题】:Laravel 4: HasManyThrough. How to access elements with where?Laravel 4:HasManyThrough。如何使用 where 访问元素?
【发布时间】:2014-07-07 09:12:58
【问题描述】:

我想要获得作者在去年创作的章节。

因此,我有一个作者、书籍和章节模型。

我通过 hasManyThrough-Relationship 进入章节,它在我的 Author-Model 中看起来像这样:

public function chapters() {
    return $this->hasManyThrough('Chapter', 'Book');
}

一切正常,因为现在我可以做这样的事情:$authors->chapters

但我想从一个作者那里得到每一章,这是去年创作的:

$chapter[$i] = $author->chapters()->where('created_at', '>', Carbon::now()->subdays(365));

问题是,它不是从章节中获得“created_at”,而是从作者那里获得“created_at”。

如果我尝试这样的事情:

$chapters = $author->chapters;

然后试试:

$chapter = $chapters->where('created_at', '>', Carbon::now()->subdays(365));

我收到消息:“不能在非对象上使用 Where”或类似的东西。

对于如何访问去年的章节,我们将不胜感激。提前致谢。

当我在这篇文章中读到时,我有一种感觉,那就是不可能,而不是不善言辞。我可能在这里错了: Laravel / Eloquent : hasManyThrough WHERE

编辑: 这是我所有的模型、控制器和迁移:

http://help.laravel.io/193c1da926554da8448cad1cc3289535acc53574

【问题讨论】:

  • 对不起,我不得不删除我的答案。 withTimestamps() 只能在 hasMany()belongsToMany() 关系上调用。

标签: php laravel


【解决方案1】:

另一种解决方案是预先加载您与约束的关系(建议您缓解 N + 1 查询问题)

$author = Author::find(1);

// eager loading
$author->load(array('chapters' => function ($query)
{
    $query->where('chapters.created_at', '>', Carbon::now()->subdays(365))->get();
}));

// Get chapters of an author
$chapters = author->chapters;

【讨论】:

    【解决方案2】:

    试试

    $chapters = $author->chapters();
    

    然后

    echo '<pre>';
    dd($chapters->where('created_at', '>', Carbon::now()->subdays(365))->get());
    

    在 hasmanythrough 关系上指定列名

    public function chapters()
    {
        return $this->hasManyThrough('Chapter', 'Book', 'author_id', 'book_id');
    }
    

    【讨论】:

    • 谢谢。我仍然收到一条错误消息,指出“违反完整性约束:1052”。进一步的研究表明,我正在调用一个列名,它也出现在其他表中,因此我必须指定该表。不确定,如果这是正确的,因为我不知道在使用“where”方法时如何指定表名
    • 顺便说一句。我在 OP 中的 EDIT 中添加了所有控制器、模型和迁移
    • where方法中用chapters.created_at替换created_at
    • 应该已经在读取章节的 created_at 值了吧?
    猜你喜欢
    • 2014-08-14
    • 2015-01-31
    • 2016-07-13
    • 1970-01-01
    • 2022-12-06
    • 2019-03-28
    • 2015-05-29
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多