【问题标题】:Laravel, Many-to-many relationships, find() vs where()Laravel,多对多关系,find() vs where()
【发布时间】:2016-09-08 20:29:03
【问题描述】:

我有一个 Laravel 4.2 站点,其数据库布局非常简单。重要的部分是具有多对多关系的People 模型和Subject 模型。这有效,例如:

$id = 5;
$ppl = Subject::find($id)->people()->orderBy('lastname')->get();

返回给定Subject 的所有People。我要做的不是为 single 主题找到所有People,而是为 multiple 主题找到所有人。我的猜测是这样的:

$subjects = array(5, 6, 7);
$ppl = Subject::whereIn('id', $subjects)->people()->orderBy('lastname')->get();

这不起作用(未定义的方法 people())。以下(未定义财产的人)也没有:

$ppl = Subject::whereIn('id', $subjects)->people->orderBy('lastname')->get();

我目前只是使用原始 SQL 来解决这个问题。如何在模型上使用 where()whereIn() 调用的雄辩关系?或者,有没有更好的方法来解决这个问题。

编辑:这是我用来获取给定主题数组的 people.id 列表的原始 SQL:

SELECT 
  DISTINCT(people.id) 
  FROM people 
  LEFT JOIN person_subject ON person_subject.person_id=people.id 
  WHERE 
    person_subject.subject_id IN (%s) AND 
    deleted_at IS NULL

【问题讨论】:

    标签: laravel laravel-4 orm eloquent


    【解决方案1】:

    您需要加入表格以按姓氏排序:

    $ppl = Subject::whereIn('id', $subjects)
        ->select('subjects.*')
        ->distinct()
        ->join('people', 'people.id', '=', 'subjects.people_id')
        ->orderBy('lastname')
         ->get();
    

    检查所有表名,因为我不知道它们,以上只是一个示例。

    【讨论】:

      【解决方案2】:

      你雄辩的关系应该让你渴望加载与某个主题相关的人,你可以这样做:

      Subject::whereIn('id', $subjects)->with('people')->orderBy('lastname')->get();
      

      这将返回与主题相关的人员。

      如果这不起作用,请告诉我。

      【讨论】:

      • 该行返回Column not found: 1054 Unknown column 'lastname' in 'order clause' (SQL: select * from ``subjects`` where ``id`` in (141, 164, 100) order by ``last name`` asc)
      猜你喜欢
      • 2021-10-02
      • 1970-01-01
      • 2016-12-31
      • 2019-11-24
      • 2018-06-15
      • 1970-01-01
      • 2018-01-22
      • 2016-02-26
      • 2016-01-04
      相关资源
      最近更新 更多