【发布时间】: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