【问题标题】:How to get all the instances of one object in a many-to-many relationship in Laravel?如何在 Laravel 中以多对多关系获取一个对象的所有实例?
【发布时间】:2019-08-02 23:31:59
【问题描述】:

我有两个以多对多关系相互关联的表。我已经在双方都使用方法 $this->belongsToMany() 建立了查询。

一个表叫做Device,另一个叫做Pos。我想使用 Eloquent 在中间表中访问与该 Pos 相关的所有设备实例。

这是设备型号:

public function pos()
    {
        return $this->belongsToMany('App\Pos', 'devices_pos')->withTimestamps();
    }

这是 Pos 模型:

public function devices()
    {
        return $this->belongsToMany('App\Device', 'devices_pos')->withTimestamps();
    }

我不想直接对“devices_pos”表进行数据库查询。我想用 Eloquent 的方式来做。

【问题讨论】:

标签: laravel eloquent


【解决方案1】:

访问关系后使用pivot属性访问中间表

$pos = Pos::find($id);

foreach ($pos->devices as $device) {
    echo $device->pivot->created_at; //returns created_at on the intermedite table 'devices_pos'
}

【讨论】:

    【解决方案2】:

    您可以使用关系从 Pos 访问所有设备:

    $pos = Pos::find($id);
    $pos->devices; // this will return all the devices from that pos
    

    您可以循环访问每个设备的每个属性:

    foreach($pos->devices as $device)
    {
    echo $device->anyDeviceAttribute;
    }
    

    欲了解更多信息:Docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-10
      • 2016-07-20
      • 2019-07-17
      • 2016-10-03
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 2019-12-22
      相关资源
      最近更新 更多