【问题标题】:Eloquent Subquery雄辩的子查询
【发布时间】:2014-04-12 07:32:20
【问题描述】:

我在学生桌设备桌之间有多对多的关系(一个学生在许多设备上表演,一个设备有很多学生)。我有一个 student_results 表,它有一个复合主键(student_idapparatus_id)和一个名为 results 的第三个字段。

我编写了一个查询来查找学生没有有结果的所有设备。我给出的示例是针对 id = 121 的学生。 子查询是。

SELECT apparatus_id, strapparatus_name FROM apparatuss 
WHERE apparatus_id <> ALL(SELECT apparatus_id FROM student_results 
WHERE student_id =' . 121 . ')';

我想用 Eloquent (Laravel 4.1) 来写这篇文章。

非常感谢任何帮助。

【问题讨论】:

    标签: laravel-4 eloquent


    【解决方案1】:

    假设您已经设置了 Eloquent 模型 ApparatusStudentResult,这是一种方法:

    Apparatus::whereNotIn(
        'apparatus_id',
        StudentResult::where('student_id', 121)->lists('apparatus_id')
    )->get('apparatus_id', 'strapparatus_name');
    

    或者,如果您的 student_results 表没有模型,您可以:

    Apparatus::whereNotIn(
        'apparatus_id',
        DB::table('student_results')->where('student_id', 121)->lists('apparatus_id'); 
    )->get(array('apparatus_id', 'strapparatus_name'));
    

    【讨论】:

    • 非常感谢您的回复 Antonio。我确实有一个 Apparatus 模型,但我正在为 student_results 使用数据透视表,因此我没有 student_results 的模型。下面是我的解决方案。我将它放在 route.php 文件中以在实现之前测试代码。 $results2 = DB::table('student_results')->where('student_id', 121)->lists('apparatus_id'); $results = Apparatus::whereNotIn('apparatus_id', $results2)->get(); foreach($results as $tempresult){ print '
    • ' . $tempresult->apparatus_id 。 ' ' 。 $tempresult->strapparatus_name; }
  • 谢谢安东尼奥。我试试那个确切的代码。谢谢。 ->get('apparatus_id', 'strapparatus_name'); 有一个问题。所以我不得不简单地使它 ->get();错误消息是:传递给 Illuminate\Database\Grammar::columnize() 的参数 1 必须是给定字符串类型的数组。再次感谢 PS没有“;”在列表末尾('apparatus_id')
  • 将其更改为数组应使其按原样工作。而且没有“;”在那里,它是 whereNotIn 的第二个参数。
  • 出色的安东尼奥!非常感谢!
  • 你知道吗,@AntonioCarlosRibeiro?事实证明,就我而言,当我只想使用 -&gt;get('id'); 从模型中获取 ID 以便使用 -&gt;whereIn($ids)-&gt;update([array]) 应用到另一个模型时,我收到了错误 Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given。所以我将get() 更改为lists(),现在它可以工作了! ☺ .... 但是为什么呢?
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签