Laravel,Eloquent:从多对多关系中获取所有条目

时间:2017-07-14 08:20:01

标签: php laravel eloquent many-to-many

我有两个由数据透视表链接的表(使用自定义迁移):

兴趣表:

ID | label

人员表:

ID | label

PersonH​​asInterest表(自定义迁移):

InterestID | PersonID | notes

如何从数据透视表中获取所有记录(加入了人员和兴趣)?我不想获得一个人或所有有兴趣的人的所有兴趣,但是所有参与(带有联接)的数据透视表。

2 个答案:

答案 0 :(得分:0)

尝试定义这样的枢轴模型:

<?php

...
use Illuminate\Database\Eloquent\Relations\Pivot;
...
class PersonHasInterest extends Pivot
{
    protected $table = '...'; // table name
}

然后使用它:PersonHasInterest::all();

答案 1 :(得分:0)

即使Pivot扩展Model,也无法在Pivot - 对象上调用标准模型函数。 Issue on Github

我提出的是使用DB-Facade执行select语句,如下所示:

DB::table('person_has_interest')
    ->join('interest', 'person_has_interest.interest_id', '=', 'interest.id')
    ->join('person', 'person_has_interest.person_id', '=', 'person.id')
    ->get(); // further manipulation like select possible 
相关问题