laravel - 根据 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 的所有产品列表
解决方案
实际上我在这里回答我自己的问题,因为我找到了确切的方法
$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();
}
推荐阅读
- python - PyYAML 不解析所有示例
- ruby-on-rails - 如何从 Rails 执行 shell 命令?
- javascript - React 压缩渲染,导致即使调用了 componentDidUpdate 也不更新组件
- swift - 如何在 Swift 中解开字符串以修复错误?
- api - OAuth中授权码的用途是什么
- ionic-framework - 离子滑块中的图像放大和缩小
- spring - Spring Kafka Listener 中保存的实体不会在事务测试中回滚
- javascript - 函数内部声明的数组是静态的?
- javascript - 使用 Javascript 变量作为 EJS 数组的索引 - NODEJS
- javascript - 无法访问 php 中发布的数据