laravel - 如何在 Laravel 中获取多对多关系中一个对象的所有实例?

标签 laravel eloquent

我有两个以多对多关系相互关联的表。我已经在两侧使用 $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/

相关文章:

mysql - laravel mysql 连接数据库失败

php - 在 Laravel 中计算坐标距离

mysql - 使用 DB Facade 仅插入数据库一次

php - 多个重复查询 - Laravel

php - 如何将我的消息添加到 Laravel 4.2 中的 $errors 变量

php - Laravel 创建或更新无需两次查询

php - 如何在 Laravel 中使用数据库进行邮件设置

php - 为多个站点和每个项目安装使用 vagrant 和 homestead

php - 拉拉维尔 6.2 : I get the same Id from different data in index() method

laravel - Laravel Eloquent获取结果,关系数据为空