代码之家  ›  专栏  ›  技术社区  ›  Mostafa Norzade Sachin Shanbhag

在laravel中创建子查询

  •  0
  • Mostafa Norzade Sachin Shanbhag  · 技术社区  · 6 年前

    如何将以下SQL查询转换为Laravel查询生成器?

    select
        *
    from
        users
    where
        EXISTS (
        SELECT
            *
        from
            posts
        where
            posts.created_by = users.id )
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Mozammil    6 年前

    以下方面应起作用:

    DB::table('users')
        ->whereExists(function ($query) {
            $query->select('*')
                ->from('posts')
                ->whereRaw('posts.created_by = users.id');
        })
        ->get();
    

    你也可以看看 documentation.

        2
  •  1
  •   Ahmed Nour Jamal El-Din    6 年前

    你可以用 has 方法与对应关系。

    为此:

    1. User Post 模型。
    2. 使用者 有很多 邮递 具有 posts 作为关系和 使用者 .
    3. 方法如下: User::has('posts')->get() 帖子 中关系的名称 使用者

    从…起 docs :

    访问模型的记录时,您可能希望根据关系的存在限制结果。例如,假设您想要检索至少有一条评论的所有博客文章。为此,您可以将关系的名称传递给has和orHas方法:

    // Retrieve all posts that have at least one comment...
    $posts = App\Post::has('comments')->get();