我有两个以多对多关系相互关联的表。我已经在两侧使用 $this->belongsToMany() 方法建立了查询。
一个表称为Device,另一个表称为Pos。我想使用 Eloquent 访问中间表中与该 Pos 相关的所有 Device 实例。
这是设备型号:
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 方式做到这一点。
最佳答案
您可以使用以下关系从 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
关于laravel - 如何在 Laravel 中获取多对多关系中一个对象的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55122414/