php - Laravel 预加载 - 关系查询

标签 php laravel orm laravel-4

假设我有这 3 个表 Blog、Post、Comment,其中有相应的模型 Blog、Post、Comment。
不,这里是他们之间的关系:

Blog has many Post,  posts()
Post belongs to Blog, blog()  
Post has many Comment, comments() 
Comment belongs to Post post()

现在我想执行这样的查询:

Blog::with(array('posts.comments' => function($q)
    {
       //query Post columns
    })->find(1);

据我所知,$q 对应于 Comment 表。有什么办法可以查询Post表吗?

最佳答案

像这样查询嵌套关系:

$blog = Blog::with(['posts' => function ($q) {
   $q->where('column','value'); // query posts table
}, 'posts.comments' => function ($q) {
   $q->where('commentsColumn','anotherValue'); // query comments table
}])->find(1);

Eloquent 将相应地加载帖子,然后才会获取这些帖子的评论。

关于php - Laravel 预加载 - 关系查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24383146/

相关文章:

php - 如何使用 php artisan 删除模型?

javascript - 创建简单的依赖 jquery 选择框不起作用

php - Laravel 4 分页计数

orm - 没有 JOIN 的生活......理解和常见做法

php - Concrete5:将文件缩略图设置为生成的图像(例如 PDF)

javascript - 当窗口进入移动 View 时,.htaccess 文件规则会扰乱菜单栏布局

php - Docker镜像的虚拟主机配置

php - 获取不是组成员的用户的逻辑

mysql - cakephp 2.x 在子查询中使用 'NOT IN'

c# - 确定 SQL Server 查询(存储过程)结果类型