首页 > 解决方案 > 根据 Laravel 中同一数据透视表中的另一列从数据透视表中获取所有值

问题描述

我想知道如何根据同一表中的另一列从数据透视表中获取所有值。例如,假设我们有两个表,即

Product User product_user(数据透视表) 数据透视表的列是:product_user 1. user_id 2. product_id 3. type(值可以是1或2)

假设我想从 user_id 为 1 且 type 也为 1 的表中检索所有行

示例数据:

user_id product_id 类型 1 1 1 1 3 1 1 76 1 2 2 2 1 21 1 1 33 2 1 23 2 1 25 1

预期结果是基于 user_id 为 1 和类型 1 的所有产品列表

标签: laravel

解决方案


实际上我在这里回答我自己的问题,因为我找到了确切的方法

$userId = 1;
$type = 1;

$user = User::where('id', $userId)->firstOrFail();
$products = $user->products() ->where('type', $type)->get();

考虑到 products() 多对多关系设置在用户模型内部:

        public function products() {
            return $this->belongsToMany(Product::class)
                ->withPivot(['type'])
                ->withTimestamps();
        }

推荐阅读