php – 一对多,然后渴望加载一个数组与Laravel雄辩ORM

使用Laravel和雄辩的ORM,我想创建属于特定用户的所有帖子和相应注释的数组或对象(已登录的).结果将与Response :: eloquent()一起使用;返回 JSON.

基本上是伪代码

All Posts by user ::with('comments').

要么

Posts by Auth::user()->id ::with('comments').

我根据用户的表,注释表和帖子表,通常使用我的数据库设置.注释表具有一个post_id,并且posts表具有一个user_id.

没有Laravel的漫长的做法就是这样:

SELECT * FROM posts WHERE user_id = 'user_id'
foreach($result as $post) {
    SELECT * FROM comments WHERE posts_id =  $post->id
    foreach($query as $comment) {
        $result[$i]->comments[$n] = $comment
    }
}

但是我想用Laravel的雄辩的ORM来完成它.

看起来你甚至不需要嵌套的加载,你只需要修改与返回的查询,所以:
$posts = Post::with('comments')->where('user_id','=',1)->get();

您可以在Eloquent系统中菊花链链接大多数方法,通常它们只是返回一个Fluent查询对象.

(我没有测试过,但我相当肯定会工作,而且,你不能在:: all()上执行它,因为调用 – > get(),你必须挖掘源代码找到这个,我不认为这个雄辩的文档提到这是正在做的.)

另外Eager Loading Documentation还包含了嵌套的加载,所以你可以加载所有的用户,他们的帖子和评论

You may even eager load nested relationships. For example,let’s
assume our Author model has a “contacts” relationship. We can eager
load both of the relationships from our Book model like so:

$books = Book::with(array('author','author.contacts'))->get();

相关文章

laravel的dd函数不生效怎么办
看不懂laravel文档咋办
安装laravel框架出现command怎么办
Laravel开发API怎么使用事务
laravel怎么构建复杂查询条件
laravel如何实现防止被下载