【问题标题】:Laravel, Eloquent: Fetch all entries from many-to-many relationLaravel,Eloquent:从多对多关系中获取所有条目
【发布时间】:2017-12-19 06:26:34
【问题描述】:

我有两个通过数据透视表链接的表(带有自定义迁移):

利息表:

ID | label

人员表:

ID | label

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

InterestID | PersonID | notes

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

【问题讨论】:

  • 为数据透视表定义一个模型,然后调用PersonHasInterest::all()?
  • 但是我如何为枢轴定义模型?
  • 和模型一样,可以指定表格属性
  • 又是什么关系?

标签: php laravel eloquent many-to-many


【解决方案1】:

尝试像这样定义一个枢轴模型:

<?php

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

那就用吧:PersonHasInterest::all();

【讨论】:

【解决方案2】:

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

我想出的是使用DB-Facade 执行选择语句,如下所示:

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 

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2016-08-04
    • 2019-06-13
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多